﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Bussiness.Entity;
using Bussiness.Manager;
using AF_ORM.CORE;
using System.IO;
using AF.Library;
using log4net;
using ComExcel = Microsoft.Office.Interop.Excel;
using System.Threading;
using Microsoft.Win32;
namespace DSC
{
    /*
     * Them Nhan vien sua chua/nhan vien tiep nha --> OK
     * Cac truong deu tu viet hoa khi lostfocus -->OK
     * Ten nguoi dang nhap hien o goc trai -->OK
     * Them nt tao phieu moi tren form chi tiet 
     * Enter xu ly giong tab-->OK
     * Them bao duong dinh ky tu 1-6-->OK
     * Tach dia chi, phuong,quan, tinh-->OK
     * Tach rieng ngay/gio-->OK
     * 
     * Search:
     *  - Cho tim theo nguoi da sua chua
     *  - Tim theo so phieu sua chua
     *  - Cho them danh muc nhan vien
     * */


    public partial class ucBill : AfUserControl
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(ucBill).Name);
        #region Properties
        DataTable tblWage1 = new DataTable();
        AF.Library.Logger log = new AF.Library.Logger("frmBill");
        public string InfoBeforeChange { set; get; }
        public string InfoAfterChange { set; get; }
        public string ServiceName
        {
            get 
            {
                return "sửa chữa";
            }
        }

        public DateTime ToDate(string date, string hour)
        {
            return new DateTime(int.Parse(date.Substring(6, 4)), int.Parse(date.Substring(3, 2)),int.Parse(date.Substring(0, 2)),int.Parse(hour.Substring(0, 2)), int.Parse(hour.Substring( 3, 2)), 0);
        }
        public DateTime InputDateTime
        {
            get 
            {
                string inputDate = dtpInput.Text.Trim();
                if (inputDate.Length == 8)
                    inputDate = inputDate.Insert(2, "/").Insert(5, "/");
                string inputTime = txtTimeInput.Text.Trim();
                if (inputTime.Length == 4)
                    inputTime = inputTime.Insert(2, ":");
                return ToDate(inputDate, inputTime);    
            }
            set
            {
                dtpInput.Text = value.ToString("dd/MM/yyyy");
                txtTimeInput.Text = value.ToString("HH:mm");
            }
        }
        public DateTime OutputDateTime
        {
            get {
                string outputDate = dtpOutput.Text.Trim();
                if (outputDate.Length == 8)
                    outputDate = outputDate.Insert(2, "/").Insert(5, "/");
                string outputTime = txtTimeOutput.Text.Trim();
                if (outputTime.Length == 4)
                    outputTime = outputTime.Insert(2, ":");
                return ToDate(outputDate, outputTime);
            }
            set
            {
                dtpOutput.Text = value.ToString("dd/MM/yyyy");
                txtTimeOutput.Text = value.ToString("HH:mm");
            }
        }
        public DateTime RepairDateTime
        {
            get {
                string repairDate = dtpRepair.Text.Trim();
                if (repairDate.Length == 8)
                    repairDate = repairDate.Insert(2, "/").Insert(5, "/");
                string repairTime = txtTimeRepair.Text.Trim();
                if (repairTime.Length == 4)
                    repairTime = repairTime.Insert(2, ":");
                return ToDate(repairDate, repairTime);
            }
            set
            {
                dtpRepair.Text = value.ToString("dd/MM/yyyy");
                txtTimeRepair.Text = value.ToString("HH:mm");
            }
        }
        public DateTime FinishDateTime
        {
            get {
                string finishDate = txtfinish.Text.Trim();
                if (finishDate.Length == 8)
                    finishDate = finishDate.Insert(2, "/").Insert(5, "/");
                string FinishTime = txtfinishtime.Text.Trim();
                if (FinishTime.Length == 4)
                    FinishTime = FinishTime.Insert(2, ":");
                return ToDate(finishDate, FinishTime); 
            }
            set
            {
                txtfinish.Text = value.ToString("dd/MM/yyyy");
                txtfinishtime.Text = value.ToString("HH:mm");
            }
        }
        #endregion 
        #region Constructor
        public ucBill()
        {
            InitializeComponent();
            ShowStatusBar("Đang load phiếu dịch vụ");
            btnSave.Tag = "Hoan thanh-them";
            CreateEventForNV();
            //MessageBox.Show(PT_ServiceBillManager.CreateInstant().GetNewServiceCode());
            LoadDefaultData();
                      
            LoadBillDetail("");
            cboProvince_SelectedIndexChanged(this, EventArgs.Empty);
            FormatText();
            CreateEvent();
            EndShowStatusBar();
            CheckPermission();
        }
        public ucBill(string billNo)
        {
            InitializeComponent();
            ShowStatusBar("Đang load phiếu dịch vụ");
            btnSave.Tag = "Hoan thanh-sua";
            CreateEventForNV();
            LoadDefaultData();
            cboProvince_SelectedIndexChanged(this, EventArgs.Empty);
            txtQOT_NO.Text = billNo;
            loadData();
            FormatText();
            CreateEvent();
            txtQOT_NO.Enabled=false;
            EndShowStatusBar();
            CheckPermission();
            btLuuTam.Enabled = btnSave.Enabled;
        }
        public ucBill(string billNo, bool IsView)
        {
            ShowStatusBar("Đang load phiếu dịch vụ");
            InitializeComponent();
            LoadDefaultData();
            CreateEvent();
            cboProvince_SelectedIndexChanged(this, EventArgs.Empty);
            txtQOT_NO.Enabled = false;
            txtQOT_NO.Text = billNo;
            loadData();
            if (IsView == true)
            {
                btnSave.Enabled = false;
                this.Text = "Xem chi tiết phiếu";
            }
            FormatText();
            EndShowStatusBar();
            CheckPermission();
        }
        #endregion
        #region Load Data
        protected void LoadDefaultData()
        {
            InputDateTime = DateTime.Now;
            OutputDateTime = DateTime.Now;
            RepairDateTime = DateTime.Now;
            FinishDateTime = DateTime.Now;

            SelectOptions option = new SelectOptions();
            //Lay thong tin tinh thanh
            option = new SelectOptions();
            option.AddSortField("P_Name", true);
            DataTable tblProv = DMS064Manager.CreateInstant().SelectAll(option);
            DataRow r = tblProv.NewRow();
            r["P_Code"] = "0";
            r["P_Name"] = "";
            tblProv.Rows.InsertAt(r, 0);
            cboProvince.DataSource = tblProv;
            cboProvince.DisplayMember = "P_Name";
            cboProvince.ValueMember = "P_Code";
            cboProvince.EndUpdate();
            cboProvince.SelectedIndex = 0;
            cboProvince.SelectedValue = 16;
            txtQOT_NO.Focus();
            LoadModel_User("");
        }

        void LoadModel_User(string BillNo)
        {
            //Load model
            PT_HondaModelEntity obj = new PT_HondaModelEntity();
            obj.IsDeleted = false;
            if (string.IsNullOrEmpty(BillNo))
                obj.IsActive = true;
            SelectOptions option = new SelectOptions();
            option.AddSortField("OrderIndex", true);

            DataTable tbl = PT_HondaModelManager.CreateInstant().SelectWithCondition(obj, option);
            DataRow dr = tbl.NewRow();
            dr["ModelCode"] = "";
            tbl.Rows.InsertAt(dr, 0);
            cboModel.DataSource = tbl;
            cboModel.DisplayMember = "ModelCode";
            cboModel.ValueMember = "ModelCode";

            //lay thong tin nguoi sua chua

            // nếu đang thêm mới phiếu thì chỉ load những user không phải là hệ thống có IsActived=1
            if (string.IsNullOrEmpty(BillNo))
                tbl = PT_AccountManager.CreateInstant().GetListAccount2(0);
            else // nếu đang sửa phiếu thì load tất cả user không phải là hệ thống
                tbl = PT_AccountManager.CreateInstant().GetListAccount4(0);
            dr = tbl.NewRow();
            dr["DisplayName"] = "";
            dr["UserId"] = 0;
            tbl.Rows.InsertAt(dr, 0);

            cboReceiveAgent.DataSource = tbl;
            cboReceiveAgent.DisplayMember = "DisplayName";
            cboReceiveAgent.ValueMember = "UserId";

            cboRepairAgent.DataSource = tbl.Copy();
            cboRepairAgent.DisplayMember = "DisplayName";
            cboRepairAgent.ValueMember = "UserId";

            cboNVKT.DataSource = tbl.Copy();
            cboNVKT.DisplayMember = "DisplayName";
            cboNVKT.ValueMember = "UserId";

            cboNVTN.DataSource = tbl.Copy();
            cboNVTN.DisplayMember = "DisplayName";
            cboNVTN.ValueMember = "UserId";

            tbl = PT_AccountManager.CreateInstant().GetListAccountExcept(0, cboRepairAgent.SelectedValue.ToString());
            dr = tbl.NewRow();
            dr["DisplayName"] = "";
            dr["UserId"] = 0;
            tbl.Rows.InsertAt(dr, 0);

            cmbKTVCungSua.DataSource = tbl.Copy();
            cmbKTVCungSua.DisplayMember = "DisplayName";
            cmbKTVCungSua.ValueMember = "UserId";

            lbNVTiepNhan.Text = tbl.Rows[0]["UserName"].ToString();
            lbKTVSuaChua.Text = tbl.Rows[0]["UserName"].ToString();
            lbNVThuNgan.Text = tbl.Rows[0]["UserName"].ToString();
            lbNVKiemTraXe.Text = tbl.Rows[0]["UserName"].ToString();

        }
        protected void LoadBillDetail(string ORDER_NO)
        {
            DataTable tbl = PT_ServiceBillDetailManager.CreateInstant().GetByBillNo(ORDER_NO);
            DataTable temp = new DataTable();
            temp.Columns.Add("ServiceCode");
            temp.Columns.Add("ServiceName");
            temp.Columns.Add("Comment");
            temp.Columns.Add("Price");
            temp.Columns.Add("SaleOffReason");
            temp.Columns.Add("SaleOff");
            temp.Columns.Add("Amount");
            temp.Columns.Add("OutPaid");
            temp.Columns.Add("IsDeleted");
            temp.Columns.Add("ID");
            temp.Columns.Add("Bill_No");
            temp.Columns.Add("AgentPrice");
            temp.Columns.Add("ServiceType");
            DataRow dr;
            string infotext = "";
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                dr = temp.NewRow();
                dr["ServiceCode"] = tbl.Rows[i]["ServiceCode"].ToString();
                dr["ServiceName"] = tbl.Rows[i]["ServiceName"].ToString();
                dr["Comment"] = tbl.Rows[i]["Comment"].ToString();
                // Giá bán
                dr["Price"] = AF.Library.Util.IsNumeric(tbl.Rows[i]["Price"].ToString()) ? String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["Price"].ToString())) : "";
                // Giá trị
                dr["AgentPrice"] = AF.Library.Util.IsNumeric(tbl.Rows[i]["AgentPrice"].ToString()) ? String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["AgentPrice"].ToString())) : "";
                if (tbl.Rows[i]["SaleOffReason"] != null && !string.IsNullOrEmpty(tbl.Rows[i]["SaleOffReason"].ToString().Trim()))
                    dr["SaleOffReason"] = tbl.Rows[i]["SaleOffReason"].ToString();
                dr["SaleOff"] = AF.Library.Util.IsNumeric(tbl.Rows[i]["SaleOff"].ToString()) ? String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["SaleOff"].ToString())) : "";
                dr["Amount"] = AF.Library.Util.IsNumeric(tbl.Rows[i]["Amount"].ToString()) ? String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["Amount"].ToString())) : "";
                dr["OutPaid"] = AF.Library.Util.IsNumeric(tbl.Rows[i]["OutPaid"].ToString()) ? String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["OutPaid"].ToString())) : "";
                dr["IsDeleted"] = tbl.Rows[i]["IsDeleted"].ToString();
                dr["ID"] = tbl.Rows[i]["ID"].ToString();
                dr["Bill_No"] = tbl.Rows[i]["Bill_No"].ToString();
                dr["ServiceType"] = tbl.Rows[i]["ServiceType"].ToString();
                temp.Rows.Add(dr);
            }
            DataColumn col = new DataColumn("Check");
            col.DataType = typeof(bool);
            col.DefaultValue = false;
            temp.Columns.Add(col);
            gridWage.Columns.Clear();
            gridWage.AutoGenerateColumns = true;
            gridWage.DataSource = temp;
            gridWage.Columns["Check"].HeaderText = "Chọn";
            gridWage.Columns["Check"].Width = 50;


            gridWage.Columns["ID"].Visible = false;
            gridWage.Columns["Bill_No"].Visible = false;
            gridWage.Columns["IsDeleted"].Visible = false;
            
            gridWage.Columns["ServiceName"].Visible = false;
            gridWage.Columns["Comment"].HeaderText = "Nội dung sửa chữa";
            gridWage.Columns["Comment"].Width = 200;
            gridWage.Columns["Comment"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            gridWage.Columns["Price"].Width = 80;
            gridWage.Columns["Price"].HeaderText = "Giá bán";
            gridWage.Columns["Price"].ReadOnly = true;
            gridWage.Columns["Price"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            gridWage.Columns.Remove("SaleOffReason");
            DataTable lst = ENUM.SaleOffReason_SelectAll();
            DataGridViewComboBoxColumn SaleOffColumn = new DataGridViewComboBoxColumn();
            SaleOffColumn.AutoComplete = true;
            SaleOffColumn.Name = "SaleOffReason";
            SaleOffColumn.HeaderText = "Lý do giảm giá";
            SaleOffColumn.DataPropertyName = "SaleOffReason";
            SaleOffColumn.DropDownWidth = 150;
            SaleOffColumn.Width = 150;
            SaleOffColumn.MaxDropDownItems = 2;
            SaleOffColumn.FlatStyle = FlatStyle.Flat;
            SaleOffColumn.DataSource = lst;
            SaleOffColumn.DisplayMember = "text";
            SaleOffColumn.ValueMember = "value";
            
            gridWage.Columns.Insert(4, SaleOffColumn);
            gridWage.Columns["SaleOffReason"].Width = 150;
            gridWage.Columns["SaleOffReason"].HeaderText = "Lý do giảm giá";
            gridWage.Columns["SaleOffReason"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            gridWage.Columns["SaleOff"].Width = 80;
            gridWage.Columns["SaleOff"].HeaderText = "Số tiền giảm giá";
            gridWage.Columns["SaleOff"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;


            gridWage.Columns["Amount"].HeaderText = "Thành tiền";
            gridWage.Columns["Amount"].Width = 100;
            gridWage.Columns["OutPaid"].HeaderText = "Chi GCN";
            gridWage.Columns["OutPaid"].Width = 100;

            gridWage.Columns.Remove("ServiceCode");
            DataTable tblService = PT_ServiceListManager.CreateInstant().GetServiceList();
            DataGridViewComboBoxColumn objColumn = new DataGridViewComboBoxColumn();
            objColumn.Name = "ServiceCode";
            objColumn.HeaderText = "Hạng mục";
            objColumn.DataPropertyName = "ServiceCode";
            objColumn.DropDownWidth = 300;
            objColumn.Width = 300;
            objColumn.MaxDropDownItems = 10;
            objColumn.FlatStyle = FlatStyle.Popup;
            objColumn.DataSource = tblService;
            objColumn.DisplayMember = "ServiceName";
            objColumn.ValueMember = "ServiceCode";
            objColumn.AutoComplete = true;
            gridWage.Columns.Insert(1, objColumn);

            gridWage.Columns["ServiceCode"].Width = 200;
            //gridWage.Columns["ServiceId"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            gridWage.Columns["AgentPrice"].Visible = false;

            // sap thu tu hien thi cot
            gridWage.Columns["ServiceCode"].DisplayIndex = 1;
            gridWage.Columns["ServiceName"].DisplayIndex = 2;
            gridWage.Columns["Comment"].DisplayIndex = 3;
            gridWage.Columns["Price"].DisplayIndex = 4;
            gridWage.Columns["SaleOffReason"].DisplayIndex = 5;
            gridWage.Columns["SaleOff"].DisplayIndex = 6;
            gridWage.Columns["Amount"].DisplayIndex = 7;
            gridWage.Columns["OutPaid"].DisplayIndex = 8;
            gridWage.Columns["ServiceType"].Visible = false;
            for (int i = 0; i < gridWage.Columns.Count-1; i++)
            {
                gridWage.Columns[i].ReadOnly = true;
            }
            gridWage.Columns["ServiceCode"].ReadOnly = false;
            AfterLoadGridHangMuc();
        }

        protected void LoadToolList(string ORDER_NO, bool isForNew)
        {
            int rIndexPTT = 0;
            int rIndexPTN = 0;
            int rIndexNhot = 0;
            DataTable tbl = Bussiness.Manager.PT_ServiceBillManager.CreateInstant().GetToolListOfBill(ORDER_NO, isForNew);
            DataView view = tbl.DefaultView;
            view.RowFilter = "ToolType=0 and IsOil = 0";
            DataTable tblPTT = view.ToTable();
           
            //    gridTool.AutoGenerateColumns = false;
            //     gridTool.DataSource = tblPTT;
            view.RowFilter = "ToolType = 1 and IsOil = 0";
            DataTable tblPTN = view.ToTable();
            view.RowFilter = "IsOil = 1";
           
            DataTable tblNhot = view.ToTable();

           
            DataTable tblTool = tbl.Clone();

            // Nhớt
            tblTool.Rows.Add(tblTool.NewRow());
            tblTool.Rows[0]["ToolName"] = "NHỚT";
            rIndexNhot = tblTool.Rows.Count - 1;


         
            int i = 1;
            for (int j = 0; j < tblNhot.Rows.Count;j++ )
            {
                tblTool.Rows.Add(tblNhot.Rows[j].ItemArray);
                tblTool.Rows[tblTool.Rows.Count - 1]["STT"] = i++;
            }

            // PT trong
            tblTool.Rows.Add(tblTool.NewRow());
            tblTool.Rows[tblTool.Rows.Count - 1]["ToolName"] = "PHỤ TÙNG TRONG";
            rIndexPTT = tblTool.Rows.Count - 1;

            /*  tblTool.Rows[0]["QTY"] = "0";
              tblTool.Rows[0]["Price"] = "0";
              tblTool.Rows[0]["SalePrice"] = "0";
              tblTool.Rows[0]["interestAmount"] = "0";
              tblTool.Rows[0]["ThanhTien"] = "0";
             * */
            i = 1;
            for (int j = 0; j < tblPTT.Rows.Count;j++ )
            {
                tblTool.Rows.Add(tblPTT.Rows[j].ItemArray);
                tblTool.Rows[tblTool.Rows.Count - 1]["STT"] = i++;
            }

            // PT ngoài
            tblTool.Rows.Add(tblTool.NewRow());
            tblTool.Rows[tblTool.Rows.Count - 1]["ToolName"] = "PHỤ TÙNG NGOÀI";
            rIndexPTN = tblTool.Rows.Count - 1;
        
            i = 1;
            for (int j=0;j < tblPTN.Rows.Count;j++)
            {
                tblTool.Rows.Add(tblPTN.Rows[j].ItemArray);
                tblTool.Rows[tblTool.Rows.Count - 1]["STT"] = i++;
            }
            gridTool.AutoGenerateColumns = false;
            gridTool.DataSource = tblTool;
            gridTool.Rows[rIndexPTT].DefaultCellStyle.BackColor = Color.LightGray;
            gridTool.Rows[rIndexPTN].DefaultCellStyle.BackColor = Color.LightGray;
            gridTool.Rows[rIndexNhot].DefaultCellStyle.BackColor = Color.LightGray;
        }
        protected void LoadToolTuMuaList(string ORDER_NO)
        {
            DataTable tbl = Bussiness.Manager.PT_ServiceBillManager.CreateInstant().GetToolListOfBill(ORDER_NO, 2);
            DataTable dt = new DataTable();
            dt.Columns.Add("STT");
            dt.Columns.Add("ToolName");
            dt.Columns.Add("Part_No");
            dt.Columns.Add("QTY");
            dt.Columns.Add("Price");
            dt.Columns.Add("SalePrice");
            dt.Columns.Add("interest");
            dt.Columns.Add("interestAmount");
            dt.Columns.Add("ThanhTien");
            DataRow dr;
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                dr = dt.NewRow();
                dr["STT"] = (i + 1).ToString();
                dr["ToolName"] = tbl.Rows[i]["Part_Name"].ToString();
                dr["Part_No"] = tbl.Rows[i]["Part_No"].ToString();
                dr["QTY"] = tbl.Rows[i]["QTY"].ToString();
                dr["Price"] = String.Format("{0:0,0.###}", !string.IsNullOrEmpty(tbl.Rows[i]["OriginalPrice"].ToString()) ? float.Parse(tbl.Rows[i]["OriginalPrice"].ToString()) : 0);
                dr["SalePrice"] = String.Format("{0:0,0.###}", !string.IsNullOrEmpty(tbl.Rows[i]["Price_After_Discount"].ToString()) ? float.Parse(tbl.Rows[i]["Price_After_Discount"].ToString()) : 0);
                dr["interest"] = String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["Price_After_Discount"].ToString()) - float.Parse(tbl.Rows[i]["OriginalPrice"].ToString()));
                float interestAmount = (float.Parse(tbl.Rows[i]["Price_After_Discount"].ToString()) - float.Parse(tbl.Rows[i]["OriginalPrice"].ToString())) * int.Parse(tbl.Rows[i]["QTY"].ToString());
                dr["interestAmount"] = String.Format("{0:0,0.###}", interestAmount);
                dr["ThanhTien"] = String.Format("{0:0,0.###}", float.Parse(tbl.Rows[i]["Price_After_Discount"].ToString()) * int.Parse(tbl.Rows[i]["QTY"].ToString()));
                dt.Rows.Add(dr);
            }
            GridPTTuMua.AutoGenerateColumns = false;
            GridPTTuMua.DataSource = dt;
        }
        protected void LoadCustomer(string ORDER_NO)
        {
            try
            {
                PT_ServiceBillEntity obj = PT_ServiceBillManager.CreateInstant().GetByBillNo(ORDER_NO);
                if (obj != null)
                {
                    txtCustName.Text = obj.CustName;
                    txtAddress.Text = obj.Address;
                    txtAddressNumber.Text = obj.AddressNumber;
                    lblTotal.Text = string.Format("{0:0,0}", obj.TotalMoney);
                    lbTienDichVu.Text = string.Format("{0:0,0}", obj.ServicePaid);
                    lbTienPhuTung.Text = string.Format("{0:0,0}", obj.ToolPaid);
                    FNumber nObj = new FNumber();
                    lblTotal2.Text = nObj.DocTienBangChu((long)obj.TotalMoney, "").ToUpper();

                    txtWard.Text = obj.Ward;
                    try
                    {
                        cboReceiveAgent.SelectedValue = obj.ReceivedBy;
                        cboRepairAgent.SelectedValue = obj.RepairedBy;
                        cmbKTVCungSua.SelectedValue = obj.RepairedBy2;
                        if (obj.RepairedBy2 != 0)
                        {
                            checkKTVCungSua.Checked = true;
                            cmbKTVCungSua.Enabled = true;
                            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cmbKTVCungSua.Text);
                            if (acc != null)
                            {
                                if (string.IsNullOrEmpty(lbKTVSuaChua.Text))
                                    lbKTVSuaChua.Text += acc.UserName;
                                else
                                    lbKTVSuaChua.Text = lbKTVSuaChua.Text.Split(new char[] { ',' })[0] + ", " + acc.UserName;
                                cmbKTVCungSua.Text = acc.DisplayName;
                            }
                        }
                        cboNVKT.SelectedValue = obj.CheckBy;
                        cboNVTN.SelectedValue = obj.Cashier;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Không tìm thấy tên nhân viên phụ trách trong hệ thống DMS");

                        //lblUserCode.Text = obj.AgentCode;
                    }

                    cboProvince.SelectedValue = obj.ProvinceCode;
                    cboDist.SelectedValue = obj.DistCode;
                    cboModel.SelectedValue = obj.Model;
                    txtPhone.Text = obj.Phone;
                    if (obj.MachineCode != null)
                    {
                        string[] strTemp = obj.MachineCode.Split(new char[] { '/' });
                        if (strTemp.Length > 0)
                            txtSK.Text = strTemp[0];
                        if (strTemp.Length > 1)
                            txtSM.Text = strTemp[1];
                    }
                    txtNumberPlate.Text = obj.NumberPlate;
                    txtSBH.Text = obj.SBH;
                    InputDateTime = obj.InputDate;
                    OutputDateTime = obj.OutputDate;
                    RepairDateTime = obj.RepairDate;
                    FinishDateTime = obj.FinishDate;
                    txtTotalKms.Text = obj.TotalKms + "";
                    lblBillCode.Text = obj.Bill_NO;
                    txtQOT_NO.Text = obj.QOT_NO;
                    txtDescription.Text = obj.Description;
                    txtYeuCauKhachHang.Text = obj.CustomerRequest;
                    txtKetQuaChanDoan.Text = obj.MotorStatus;
                    txtTinhTrangXeTruocKhiSua.Text = obj.MotorStatusBefore;
                    txtNhienLieu.Value = (decimal)obj.Fuellevel;
                }
                else
                {
                    dtpInput.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtTimeInput.Text = DateTime.Now.ToString("HH:mm");
                    dtpRepair.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtTimeRepair.Text = DateTime.Now.ToString("HH:mm");
                    txtfinish.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtfinishtime.Text = DateTime.Now.ToString("HH:mm");
                    dtpOutput.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtTimeOutput.Text = DateTime.Now.ToString("HH:mm");
                    txtCustName.Text = "";
                    txtPhone.Text = "";
                    txtAddressNumber.Text = "";
                    txtAddress.Text = "";
                    txtWard.Text = "";
                    cboDist.Text = "";
                    cboModel.Text = "";
                    txtNumberPlate.Text = "";
                    txtSBH.Text = "";
                    txtSK.Text = "";
                    txtSM.Text = "";
                    txtTotalKms.Text = "";
                    cboReceiveAgent.Text = "";
                    cboRepairAgent.Text = "";
                    checkKTVCungSua.Checked = false;
                    cmbKTVCungSua.Text = "";
                    cboNVKT.Text = "";
                    cboNVTN.Text = "";
                    lblTotal.Text = "0";
                    lbTienDichVu.Text = "0";
                    lbTienPhuTung.Text = "0";
                    lblTotal2.Text = "KHÔNG ĐỒNG";
                    txtDescription.Text = "";
                    txtYeuCauKhachHang.Text = "";
                    txtKetQuaChanDoan.Text = "";
                    txtTinhTrangXeTruocKhiSua.Text = "";
                    txtNhienLieu.Value = 0;
                    btnSave.Text = "Hoàn thành";
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        #endregion

        private bool CheckExistServiceType(string serviceType)
        {
            foreach (DataGridViewRow r in gridWage.Rows)
            {
                if (r.Cells["ServiceCode"].Value != null && r.Cells["ServiceCode"].Value.ToString() != "")
                {
                    string serviceCode = r.Cells["ServiceCode"].Value.ToString();
                    PT_ServiceListEntity seOb = PT_ServiceListManager.CreateInstant().GetByServiceCode(serviceCode);
                    if (seOb != null)
                    {
                        if (seOb.ServiceType.Equals(serviceType) == true)
                            return true;
                    }
                }
            }
            return false;
        }

        #region Save info
        private bool SaveCustomer(bool isFinished)
        {
            float TwageAmount = 0;// tong thanh tien
            float ToutPaid = 0; // tong tien gia cong ngoai
            float TaPrice = 0; // tong tien cong tho
            float TongLaiGCN = 0;// tong lai GCN
            float TongLaiPTTM = 0; // tong lai PTTM
            foreach (DataGridViewRow r in gridWage.Rows)
            {
                if (r.Cells["ServiceCode"].Value != null && r.Cells["ServiceCode"].Value.ToString() != "")
                {
                    if (r.Cells["Amount"].Value == null || r.Cells["Amount"].Value.ToString() == "")
                        r.Cells["Amount"].Value = 0;
                    if (r.Cells["OutPaid"].Value == null || r.Cells["OutPaid"].Value.ToString() == "")
                        r.Cells["OutPaid"].Value = 0;
                    if (r.Cells["Price"].Value == null || r.Cells["Price"].Value.ToString() == "")
                        r.Cells["Price"].Value = 0;
                    if (r.Cells["SaleOff"].Value == null || r.Cells["SaleOff"].Value.ToString() == "")
                        r.Cells["SaleOff"].Value = 0;
                    TwageAmount += float.Parse(r.Cells["Amount"].Value.ToString());
                    ToutPaid += float.Parse(r.Cells["OutPaid"].Value.ToString());

                    string ServiceCode = r.Cells["ServiceCode"].Value.ToString();
                    string serviceType = r.Cells["ServiceType"].Value.ToString();
                    string AgentPrice = r.Cells["AgentPrice"].Value.ToString();
                    string Price = r.Cells["Price"].Value.ToString();
                    string outPaid = r.Cells["OutPaid"].Value.ToString();
                    float chiGCN = AF.Library.Util.IsNumeric(outPaid) ? float.Parse(outPaid) : 0;
                    float thuGCN = AF.Library.Util.IsNumeric(Price) ? float.Parse(Price) : 0;
                    float LaiGCN = thuGCN - chiGCN;
                    // tien cong tho
                    float aPrice = 0;
                    if (serviceType.CompareTo("RB") == 0 || serviceType.CompareTo("KTDK") == 0)
                    {
                        // lấy giá tiền công thợ trong bảng các hạng mục sửa chữa
                        aPrice = AF.Library.Util.IsNumeric(AgentPrice) ? float.Parse(AgentPrice) : 0;
                    }
                    else if (serviceType.CompareTo("SC") == 0 || serviceType.CompareTo("HMK") == 0)
                    {
                        aPrice = AF.Library.Util.IsNumeric(Price) ? float.Parse(Price) : 0;
                    }
                    else if (serviceType.CompareTo("GCN") == 0)
                    {

                        aPrice = LaiGCN;
                    }
                    TaPrice += aPrice;
                    TongLaiGCN += LaiGCN;
                }
            }
            float OilPaid = 0;
            float toolAmount = 0;
            foreach (DataGridViewRow r in gridTool.Rows)
            {
                if (r.Cells["Amount"].Value != null && AF.Library.Util.IsNumeric(r.Cells["Amount"].Value))
                {
                    toolAmount += float.Parse(r.Cells["Amount"].Value.ToString());
                }
                if (r.Cells["IsOilT"].Value != null && !string.IsNullOrEmpty(r.Cells["IsOilT"].Value.ToString()) && (r.Cells["IsOilT"].Value.ToString().CompareTo("1") == 0 || r.Cells["IsOilT"].Value.ToString().CompareTo("True") == 0))
                {
                    OilPaid += float.Parse(r.Cells["Amount"].Value.ToString());
                }
            }
            
            float TuMuaAmount = 0;
            foreach (DataGridViewRow r in GridPTTuMua.Rows)
            {
                if (r.Cells["SalePriceTM"].Value != null && AF.Library.Util.IsNumeric(r.Cells["SalePriceTM"].Value) && r.Cells["QTYTM"].Value != null && AF.Library.Util.IsNumeric(r.Cells["QTYTM"].Value))
                    TuMuaAmount += float.Parse(r.Cells["SalePriceTM"].Value.ToString()) * float.Parse(r.Cells["QTYTM"].Value.ToString());
                if (r.Cells["interestAmountTM"].Value != null && AF.Library.Util.IsNumeric(r.Cells["interestAmountTM"].Value))
                {
                    TongLaiPTTM += float.Parse(r.Cells["interestAmountTM"].Value.ToString());
                }
            }
            PT_ServiceBillEntity obj = GetServiceEntity();
            obj.ServicePaid = TwageAmount; // tong tien hang muc dich vu
            obj.RepairPaid = TaPrice; // tong tien cong tho
            obj.ToolPaid = toolAmount + TuMuaAmount; // tong tien phu tung
            obj.OutPaid = ToutPaid; // tong tien GCN
            obj.TotalMoney = TwageAmount + toolAmount + TuMuaAmount; // tong thanh tien
            obj.TotalLaiGCN = TongLaiGCN;
            obj.TotalLaiPTTM = TongLaiPTTM;
            obj.IsFinished = isFinished;
            obj.OilPaid = OilPaid;
            if (!string.IsNullOrEmpty(obj.Bill_NO))
            {
                lblBillCode.Text = obj.Bill_NO;
                PT_ServiceBillManager.CreateInstant().Update(obj);
            }
            else
            {
                obj.Bill_NO = txtQOT_NO.Text.Trim();
                //obj.ReportDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                obj.CreatedBy = SessionLogin.UserName;
                obj.CreatedDate = DateTime.Now;
                PT_ServiceBillManager.CreateInstant().Insert(obj);
                lblBillCode.Text = obj.Bill_NO;
            }
            // Insert or update PT_Customer
            PT_CustomerEntity CusObj = GetCustomerEntity();
            InfoAfterChange = GetTotalInfo();
            if (PT_CustomerManager.CreateInstant().SelectByNumberPlate(CusObj.NumberPlate).Rows.Count > 0)
            {
                // da ton tai bien so xe nay, ta thuc hien thao tac update 
                obj.UpdatedBy = SessionLogin.UserCode;
                obj.UpdatedDate = DateTime.Now;
                PT_CustomerManager.CreateInstant().Update(CusObj);
                // history
                PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Cập nhật thông tin phiếu sửa chữa", InfoBeforeChange + " ---- " + InfoAfterChange);
            }
            else
            {
                // Chua ton tai bien so xe nay, ta thuc hien thao tac insert
                PT_CustomerManager.CreateInstant().Insert(CusObj);
                // history
                PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Thêm phiếu sửa chữa", InfoAfterChange);
            }
            return true;
        }
        private void SaveServiceDetail(ref double totalWage)
        {
            totalWage = 0;
            PT_ServiceBillDetailManager.CreateInstant().DeleteByBill_NO(lblBillCode.Text);
            for (int i = 0; i < gridWage.Rows.Count; i++)
            {
                if (gridWage.Rows[i].Cells["ServiceCode"] != null && gridWage.Rows[i].Cells["Comment"].Value != null
                    && gridWage.Rows[i].Cells["Amount"].Value != null && gridWage.Rows[i].Cells["OutPaid"].Value != null
                    && gridWage.Rows[i].Cells["SaleOff"].Value != null && gridWage.Rows[i].Cells["SaleOffReason"].Value != null
                    && gridWage.Rows[i].Cells["Price"].Value != null && gridWage.Rows[i].Cells["AgentPrice"].Value != null)
                {
                    // Mã phiếu
                    string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                    // Nội dung sửa chữa
                    string comment = gridWage.Rows[i].Cells["Comment"].Value.ToString();
                    // Thành tiền
                    string amount = gridWage.Rows[i].Cells["Amount"].Value.ToString();
                    // Chi GCN
                    string outPaid = gridWage.Rows[i].Cells["OutPaid"].Value.ToString();
                    // Số tiền giảm giá
                    string SaleOff = gridWage.Rows[i].Cells["SaleOff"].Value.ToString();
                    // Lý do giảm giá
                    string SaleOffReason = gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString();
                    // Giá bán 
                    string Price = gridWage.Rows[i].Cells["Price"].Value.ToString();
                    // Giá trị tính tiền công thợ
                    string AgentPrice = gridWage.Rows[i].Cells["AgentPrice"].Value.ToString();
                    // ServiceType
                    string serviceType = gridWage.Rows[i].Cells["ServiceType"].Value.ToString();
                    if (!string.IsNullOrEmpty(ServiceCode))
                    {
                        PT_ServiceBillDetailEntity objDetail = new PT_ServiceBillDetailEntity();
                        objDetail.ServiceCode = ServiceCode;
                        objDetail.Bill_NO = lblBillCode.Text;
                        objDetail.Amount = AF.Library.Util.IsNumeric(amount) ? float.Parse(amount) : 0;
                        float aPrice = 0;
                        if (serviceType.CompareTo("RB") == 0 || serviceType.CompareTo("KTDK") == 0)
                        { 
                            // lấy giá tiền công thợ trong bảng các hạng mục sửa chữa
                            aPrice = AF.Library.Util.IsNumeric(AgentPrice) ? float.Parse(AgentPrice) : 0;
                        }
                        else if (serviceType.CompareTo("SC") == 0 || serviceType.CompareTo("HMK") == 0)
                        {
                            aPrice = AF.Library.Util.IsNumeric(Price) ? float.Parse(Price) : 0;
                        }
                        else if (serviceType.CompareTo("GCN") == 0)
                        {
                            float chiGCN = AF.Library.Util.IsNumeric(outPaid) ? float.Parse(outPaid) : 0;
                            float thuGCN = AF.Library.Util.IsNumeric(Price) ? float.Parse(Price) : 0;
                            aPrice = thuGCN - chiGCN;
                        }
                        objDetail.Price = AF.Library.Util.IsNumeric(Price) ? float.Parse(Price) : 0;
                        objDetail.AgentPrice = aPrice;
                        objDetail.OutPaid = AF.Library.Util.IsNumeric(outPaid) ? float.Parse(outPaid) : 0;
                        objDetail.SaleOffMoney = AF.Library.Util.IsNumeric(SaleOff) ? float.Parse(SaleOff) : 0;
                        if (SaleOffReason.CompareTo("") == 0)
                            SaleOffReason = "TT";
                        objDetail.SaleOffReason = SaleOffReason;
                        objDetail.Comment = comment;
                        objDetail.CreatedBy = SessionLogin.UserName;
                        objDetail.CreatedDate = DateTime.Now;
                        PT_ServiceBillDetailManager.CreateInstant().Insert(objDetail);
                        totalWage += objDetail.Amount;
                    }
                }
            }
        }

        private void SaveToolInBill(ref double totalMoney)
        {
            totalMoney = 0;

            for (int i = 0; i < gridTool.Rows.Count; i++)
            {
                string id = gridTool.Rows[i].Cells["ToolID"].Value + "";
                // Mã phụ tùng
                string partNO = gridTool.Rows[i].Cells["Part_NO"].Value + "";
                // Tên phụ tùng
                string partName = gridTool.Rows[i].Cells["ToolName"].Value + "";
                // Thành tiền
                string amount = gridTool.Rows[i].Cells["Amount"].Value + "";
                // Giá gốc
                string Originalprice = gridTool.Rows[i].Cells["OriginalPriceT"].Value + "";
                // Giá sau khi giảm giá
                string PriceAfterDiscount = gridTool.Rows[i].Cells["Price_After_DiscountT"].Value + "";
                // Lý do giảm giá
                string DiscountReason = gridTool.Rows[i].Cells["DiscountReasonT"].Value + "";
                if (DiscountReason.CompareTo("") == 0)
                    DiscountReason = "TT";
                // Số lượng
                string QTY = gridTool.Rows[i].Cells["QTY"].Value + "";
                // Loại phụ tùng
                string ToolType = gridTool.Rows[i].Cells["ToolType"].Value + "";
                // IsOil
                string IsOil = gridTool.Rows[i].Cells["IsOilT"].Value + "";
                // Cost
                string Cost = gridTool.Rows[i].Cells["Cost"].Value + "";
                //Neu la tool moi load vao thi moi insert
                if (!string.IsNullOrEmpty(id))
                {
                    PT_ToolInBillEntity objDetail = new PT_ToolInBillEntity();
                    objDetail.BillNo = lblBillCode.Text;
                    objDetail.Part_No = partNO;
                    objDetail.Part_Name = partName;
                    objDetail.OriginalPrice = float.Parse(Originalprice);
                    objDetail.Price_After_Discount = float.Parse(PriceAfterDiscount);
                    objDetail.DiscountReason = DiscountReason;
                    objDetail.QTY = int.Parse(QTY);
                    objDetail.Amount = float.Parse(amount);
                    objDetail.ToolType = int.Parse(ToolType);
                    objDetail.Cost = float.Parse(Cost);
                    if (IsOil.CompareTo("1")==0 || IsOil.CompareTo("True")==0)
                        objDetail.IsOil = true;
                    PT_ToolInBillManager.CreateInstant().Insert(objDetail);
                    totalMoney += float.Parse(gridTool.Rows[i].Cells["Amount"].Value + "");
                }
            }
        }

        private void SaveToolTM(ref double totalMoney)
        {
            totalMoney = 0;
            // xoa phu tung tu mua cu
            PT_ToolInBillManager.CreateInstant().DeleteByBillNo_And_ToolType(lblBillCode.Text, 2);
            string errors = "";
            for (int i = 0; i < GridPTTuMua.Rows.Count; i++)
            {
                string error = "";
                if (GridPTTuMua.Rows[i].Cells["STTTM"].Value != null)
                {
                    string partNO = GridPTTuMua.Rows[i].Cells["Part_NOTM"].Value + "";
                    if (string.IsNullOrEmpty(partNO))
                    {
                        if (!string.IsNullOrEmpty(error))
                            error += ", ";
                        error += "mã phụ tùng";
                    }
                    string partName = GridPTTuMua.Rows[i].Cells["ToolNameTM"].Value + "";
                    if (string.IsNullOrEmpty(partName))
                    {
                        if (!string.IsNullOrEmpty(error))
                            error += ", ";
                        error += "tên phụ tùng";
                    }
                    // so luong 
                    string QTY = GridPTTuMua.Rows[i].Cells["QTYTM"].Value + "";
                    if (string.IsNullOrEmpty(QTY))
                    {
                        if (!string.IsNullOrEmpty(error))
                            error += ", ";
                        error += "Số lượng";
                    }
                    // gia von 
                    string originalPrice = GridPTTuMua.Rows[i].Cells["PriceTM"].Value + "";
                    if (string.IsNullOrEmpty(originalPrice))
                    {
                        if (!string.IsNullOrEmpty(error))
                            error += ", ";
                        error += "giá vốn";
                    }
                    // gia ban
                    string price = GridPTTuMua.Rows[i].Cells["SalePriceTM"].Value + "";
                    if (string.IsNullOrEmpty(price))
                    {
                        if (!string.IsNullOrEmpty(error))
                            error += ", ";
                        error += "giá bán";
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        // thanh tien
                        float amount = float.Parse(price) * float.Parse(QTY);
                        PT_ToolInBillEntity objDetail = new PT_ToolInBillEntity();

                        objDetail.BillNo = lblBillCode.Text;
                        objDetail.Part_No = partNO;
                        objDetail.Part_Name = partName;
                        objDetail.Price_After_Discount = float.Parse(price);
                        objDetail.QTY = (int)float.Parse(QTY);
                        objDetail.Amount = amount;
                        objDetail.OriginalPrice = float.Parse(originalPrice);
                        objDetail.ToolType = 2;
                        if (PT_OILManager.CreateInstant().GetByCode(partNO).Count > 0)
                            objDetail.IsOil = true;
                        PT_ToolInBillManager.CreateInstant().Insert(objDetail);

                        totalMoney += amount;
                    }
                    else
                        errors += "Dòng " + (i + 1).ToString() + " Chưa được lưu vì thiếu các thông tin sau :" + error + "\r\n";
                }
            }
            if (!string.IsNullOrEmpty(errors))
                MessageBox.Show("Thông báo phần phụ tùng tự mua :\r\n" + errors);
        }
        private bool SaveInfo(bool IsFinished)
        {
            if (!CheckValidation(IsFinished))
                return false;
            // Lưu thông tin phiếu (khách hàng, nhân viên sửa chữa, tiếp nhận, kiểm tra, thu ngân)
            SaveCustomer(IsFinished);

            double amount = 0;
            double toolAmount = 0;
            double TMToolAmount = 0;
            // Lưu hạng mục sửa chữa
            SaveServiceDetail(ref amount);
            // Xóa phụ tùng
            PT_ServiceBillEntity BillObj = PT_ServiceBillManager.CreateInstant().GetByQOT_NO(txtQOT_NO.Text.Trim());
            if (BillObj != null)
            {
                PT_ToolInBillManager.CreateInstant().DeleteByBillNo(BillObj.Bill_NO);
            }
            // Lưu phụ tùng
            SaveToolInBill(ref toolAmount);
            
            // Lưu phụ tùng tự mua
            SaveToolTM(ref TMToolAmount);
            if (IsFinished == true)
                MessageBox.Show("Đã lưu phiếu hoàn thành");
            else
                MessageBox.Show("Đã lưu phiếu tạm");
            return true;
        }
        // luu hoan thanh
        private void btnSave_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang lưu phiếu dịch vụ");
            if (SaveInfo(true))
            {
                if (!string.IsNullOrEmpty(lblBillCode.Text)) 
                    LoadCustomer(lblBillCode.Text);
              //  RaiseChangeDataEvent();
                ResetForm();
            }
            EndShowStatusBar();
        }

        // luu tam
        private void btLuuTam_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang lưu phiếu dịch vụ");
            if (SaveInfo(false))
            {
                if (!string.IsNullOrEmpty(lblBillCode.Text))
                    LoadCustomer(lblBillCode.Text);
              //  RaiseChangeDataEvent();
                ResetForm();
            }
            EndShowStatusBar();
        }

        #endregion
        private void FormatText()
        {
            txtQOT_NO.CharacterCasing = CharacterCasing.Upper;

            dtpInput.CharacterCasing = CharacterCasing.Upper;
            txtTimeInput.CharacterCasing = CharacterCasing.Upper;

            dtpOutput.CharacterCasing = CharacterCasing.Upper;
            txtTimeOutput.CharacterCasing = CharacterCasing.Upper;

            dtpRepair.CharacterCasing = CharacterCasing.Upper;
            txtTimeRepair.CharacterCasing = CharacterCasing.Upper;

            txtfinish.CharacterCasing = CharacterCasing.Upper;
            txtfinishtime.CharacterCasing = CharacterCasing.Upper;

            txtCustName.CharacterCasing = CharacterCasing.Upper;
            txtPhone.CharacterCasing = CharacterCasing.Upper;
            txtAddressNumber.CharacterCasing = CharacterCasing.Upper;
            txtAddress.CharacterCasing = CharacterCasing.Upper;
            txtWard.CharacterCasing = CharacterCasing.Upper;
            txtNumberPlate.CharacterCasing = CharacterCasing.Upper;
            txtSBH.CharacterCasing = CharacterCasing.Upper;
            txtSK.CharacterCasing = CharacterCasing.Upper;
            txtSM.CharacterCasing = CharacterCasing.Upper;
            txtTotalKms.CharacterCasing = CharacterCasing.Upper;
        }
        
        string GetDateString(string text)
        {
            text = text.Replace("/", "");
            text = text.Replace("-", "");
            if (text.Trim().Length != 8)
                return "";
            string date = text.Substring(4, 4) + "/" + text.Substring(2, 2) + "/" + text.Substring(0, 2);
            return date;
        }
        void CreateEventForNV()
        {
            cboReceiveAgent.TextChanged += new EventHandler(cboReceiveAgent_TextChanged);
            cboRepairAgent.TextChanged += new EventHandler(cboRepairAgent_TextChanged);
            cmbKTVCungSua.TextChanged += new EventHandler(cmbKTVCungSua_TextChanged);
            cboNVKT.TextChanged += new EventHandler(cboNVKT_TextChanged);
            cboNVTN.TextChanged += new EventHandler(cboNVTN_TextChanged);
        }
        void CreateEvent()
        {
            
            //txtQOT_NO.LostFocus += new EventHandler(txtOrderNo_LostFocus);

            dtpInput.LostFocus += new EventHandler(dtp_LostFocus);
            dtpRepair.LostFocus += new EventHandler(dtp_LostFocus);
            txtfinish.LostFocus += new EventHandler(dtp_LostFocus);
            dtpOutput.LostFocus += new EventHandler(dtp_LostFocus);

            dtpInput.Enter += new EventHandler(dtp_Focus);
            dtpRepair.Enter += new EventHandler(dtp_Focus);
            txtfinish.Enter += new EventHandler(dtp_Focus);
            dtpOutput.Enter += new EventHandler(dtp_Focus);
            
            txtTimeInput.LostFocus += new EventHandler(txt_FormatTime_LostFocus);
            txtTimeRepair.LostFocus += new EventHandler(txt_FormatTime_LostFocus);
            txtTimeOutput.LostFocus += new EventHandler(txt_FormatTime_LostFocus);
            txtfinishtime.LostFocus += new EventHandler(txt_FormatTime_LostFocus);

            txtTimeInput.Enter += new EventHandler(txt_FormatTime_Focus);
            txtTimeRepair.Enter += new EventHandler(txt_FormatTime_Focus);
            txtTimeOutput.Enter += new EventHandler(txt_FormatTime_Focus);
            txtfinishtime.Enter += new EventHandler(txt_FormatTime_Focus);

            txtQOT_NO.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtCustName.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtAddress.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtSK.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtNumberPlate.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtSBH.LostFocus += new EventHandler(txt_ToUper_LostFocus);
            txtWard.LostFocus += new EventHandler(txt_ToUper_LostFocus);

            gridWage.UserAddedRow += new DataGridViewRowEventHandler(gridWage_UserAddedRow);
            gridWage.CellMouseDown += new DataGridViewCellMouseEventHandler(gridWage_CellMouseDown);

            cboReceiveAgent.Leave += new EventHandler(cboAgent_LostFocus);
            cboRepairAgent.Leave += new EventHandler(cboAgent_LostFocus);
            cboNVKT.Leave += new EventHandler(cboAgent_LostFocus);
            cboNVTN.Leave += new EventHandler(cboAgent_LostFocus);
            cboProvince.Leave += new EventHandler(cboProvince_LostFocus);
            cboModel.Leave += new EventHandler(cboModel_LostFocus);
            cboDist.Leave += new EventHandler(cboDist_LostFocus);
            cmbKTVCungSua.Leave += new EventHandler(cboAgent_LostFocus);

            checkKTVCungSua.CheckedChanged += new EventHandler(checkKTVCungSua_CheckedChanged);

            // progress bar
            txtNhienLieu.Leave += new EventHandler(txtNhienLieu_LostFocus);
        }

        void checkKTVCungSua_CheckedChanged(object sender, EventArgs e)
        {
            cmbKTVCungSua.Enabled = checkKTVCungSua.Checked;
        }

        void gridWage_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
            }
            catch (Exception ex)
            {

            }
        }
        private void loadData()
        {
            // created by toannb
            // created date 9/6/2012
            // Load Model va User vo list
            if (!string.IsNullOrEmpty(txtQOT_NO.Text.Trim())) // kiểm tra số phiếu đã được nhập vào textbox chưa
            {
                // Kiểm tra phiếu sửa chữa có tồn tại bên db của mình chưa 
                PT_ServiceBillEntity objCond = new PT_ServiceBillEntity();
                objCond.IsDeleted = false;
                objCond.QOT_NO = txtQOT_NO.Text.Trim();
                List<PT_ServiceBillEntity> lst = PT_ServiceBillManager.CreateInstant().SelectWithConditionLST(objCond);
                if (lst != null && lst.Count > 0)
                {
                    txtQOT_NO.Enabled = false;
                    LoadModel_User(txtQOT_NO.Text.Trim());
                    // Nếu phiếu đã tồn tại thì kiểm tra tiếp tình trạng phiếu đã hoàn tất hay chưa
                    // Chú ý: hoàn tất rồi : tức là các phiếu đã được nhâp phụ tùng trong kho của DMS
                    //        Ngược lại: phiếu tạm là các phiếu chỉ mới lưu tạm một vài thông tin mà chưa lấy được phụ tùng từ DMS
                    PT_ServiceBillEntity obj = lst[0];
                    if (obj.IsFinished == true) // phiếu đang ở trạng thái hoàn thành rồi
                    {
                        // Load dữ liệu phụ tùng từ db của mình                        
                        LoadToolList(txtQOT_NO.Text, false);
                        btnSave.Tag = "Hoan thanh-sua";
                        btLuuTam.Tag = "Luu tam-sua";
                    }
                    else // Phiếu ở trạng thái chưa hoàn thành
                    {
                        // Load dữ liệu phụ tùng từ db của DMS
                        LoadToolList(txtQOT_NO.Text, true);
                        btnSave.Tag = "Hoan thanh-them";
                        btLuuTam.Tag = "Luu tam-them";
                    }
                    LoadCustomer(obj.Bill_NO);
                    LoadBillDetail(obj.Bill_NO);
                    LoadToolTuMuaList(obj.Bill_NO);
                    lblBillCode.Text = txtQOT_NO.Text.Trim();
                    InfoBeforeChange = GetTotalInfo();
                    if (this.Parent != null)
                        //hien thi cai Title tab o tren khi sua chua phieu
                        this.Parent.Text = "Sửa phiếu-" + txtQOT_NO.Text;
                    txtQOT_NO.Enabled = false;
                    CheckPermission();
                    return;
                }
                else // Nếu phiếu chưa tồn tại trong db của mình tức là phiếu này là phiếu mới hoàn toàn -> không làm gì tiếp theo cả
                {
                    LoadToolList(txtQOT_NO.Text.Trim(), true);
                    LoadBillDetail(txtQOT_NO.Text.Trim());
                    LoadCustomer(txtQOT_NO.Text.Trim());
                    lblBillCode.Text = "";
                    if (gridTool.RowCount > 3)
                        txtQOT_NO.Enabled = false;
                    this.Parent.Text = "Thêm phiếu-" + txtQOT_NO.Text;                
                    return;
                }
            }
            else
                this.Parent.Text = "Thêm phiếu";
        }

        #region Lost focus + focus
        void txtOrderNo_LostFocus(object sender, EventArgs e)
        {
            ShowStatusBar("Đang load phiếu dịch vụ");
            loadData();
            EndShowStatusBar();
        }
        void txtNhienLieu_LostFocus(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNhienLieu.Text.Trim()))
                progressBarNhienLieu.Value = 0;
            else
                progressBarNhienLieu.Value = (int)txtNhienLieu.Value;
        }
        void dtpInput_LostFocus(object sender, EventArgs e)
        {
            dtpOutput.Text = dtpInput.Text;
            dtpRepair.Text = dtpInput.Text;
            txtfinish.Text = dtpInput.Text;
        }

        void txt_FormatTime_LostFocus(object sender, EventArgs e)
        {
            TextBox txt = ((TextBox)sender);
            if (txt.Text.Trim() == "")
            {
                txt.Text = "00:00";
                return;
            }
            if (txt.Text.Length < 4)
            {
                MessageBox.Show("Vui lòng nhập đúng định dạng hhmm", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txt.Text = DateTime.Now.ToString("hh:mm");
                return;
            }
            txt.Text = txt.Text.Substring(0, 2) + ":" + txt.Text.Substring(2, 2);
        }
        void txt_FormatTime_Focus(object sender, EventArgs e)
        {
            TextBox txt = ((TextBox)sender);
            txt.Text = txt.Text.Replace(":", "");
        }

        void txt_ToUper_LostFocus(object sender, EventArgs e)
        {
            TextBox txt = ((TextBox)sender);
            txt.Text = txt.Text.ToUpper();
        }

        void dtp_LostFocus(object sender, EventArgs e)
        {
            TextBox txt = ((TextBox)sender);
            string date = GetDateString(txt.Text);

            if (date == "" || !AF.Library.FDateTime.IsDate(date))
            {
                MessageBox.Show("Vui lòng nhập đúng định dạng ddMMyyyy hhmm", "Cảnh báo nhập sai dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //txt.Focus();
                txt.Text = DateTime.Now.ToString("dd/MM/yyyy");
                return;
            }
            txt.Text = DateTime.Parse(date).ToString("dd/MM/yyyy");
        }

        void dtp_Focus(object sender, EventArgs e)
        {
            TextBox txt = ((TextBox)sender);
            if (txt.Text != "")
            {
                txt.Text = txt.Text.Replace(":", "");
                txt.Text = txt.Text.Replace("/", "");
            }
        }
        #endregion

        void gridWage_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["IsDeleted"].Value = false;
        }
        
        public bool CheckValidation(bool isFinished)
        {
            // Chỉ check dữ liệu khi lưu phiếu với trạng thái là hoàn thành.
            // Nếu là phiếu tạm chỉ cần check có mã phiếu là có thể lưu được, ko quan tâm các trường khác có đủ hay ko 
            
            // Kiểm tra mã phiếu
            if (txtQOT_NO.Text.Trim() == "")
            {
                MessageBox.Show("Vui lòng nhập mã phiếu trước khi thực hiện các thao tác khác", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtQOT_NO.Focus();
                return false;
            }
            // Nếu lưu phiếu với tình trạng hoàn thành
            if (isFinished==true)
            {
                // ngày giờ nhận
                if (string.IsNullOrEmpty(dtpInput.Text.Trim())|| string.IsNullOrEmpty(txtTimeInput.Text.Trim()))
                {
                    MessageBox.Show("Nhập ngày giờ nhận xe", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpInput.Focus();
                    return false;
                }
                string ngayNhanxe = dtpInput.Text.Trim();
                if (ngayNhanxe.Length < 8)
                {
                    MessageBox.Show("Ngày nhận xe chưa đúng định dạng dd/MM/yyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpInput.Focus();
                    return false;
                }
                else if(ngayNhanxe.Length==8)
                {
                    ngayNhanxe = ngayNhanxe.Insert(2, "/").Insert(5, "/");
                }
                string gioNhanxe = txtTimeInput.Text.Trim();
                if (gioNhanxe.Length < 4)
                {
                    MessageBox.Show("Giờ nhận chưa xe đúng định dạng mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtTimeInput.Focus();
                    return false;
                }
                else if (gioNhanxe.Length == 4)
                {
                    gioNhanxe = gioNhanxe.Insert(2, ":");
                }
                if (!AF.Library.FDateTime.IsDate(ngayNhanxe + " " + gioNhanxe + ":00"))
                {
                    MessageBox.Show("Ngày giờ nhận chưa xe đúng định dạng dd/MM/yyyy mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpInput.Focus();
                    return false;
                }
                else
                {
                    DateTime inputDate = AF.Library.FDateTime.ConvertDate(ngayNhanxe + " " + gioNhanxe + ":00");
                    if (inputDate.Hour > 20 || inputDate.Hour < 7)
                    {
                        MessageBox.Show("Giờ nhận xe nằm ngoài thời gian làm việc", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtTimeInput.Focus();
                        return false;
                    }
                }

                // Bắt đầu sửa
                if(string.IsNullOrEmpty(dtpRepair.Text.Trim()) || string.IsNullOrEmpty(txtTimeRepair.Text.Trim()))
                {
                    MessageBox.Show("Nhập ngày giờ bắt đầu sửa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpRepair.Focus();
                    return false;
                }
                string ngayBatDauSua = dtpRepair.Text.Trim();
                if (ngayBatDauSua.Length < 8)
                {
                    MessageBox.Show("Ngày bắt đầu sửa chưa đúng định dạng dd/MM/yyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpRepair.Focus();
                    return false;
                }
                else if (ngayBatDauSua.Length == 8)
                {
                    ngayBatDauSua = ngayBatDauSua.Insert(2, "/").Insert(5, "/");
                }
                string gioBatDauSua = txtTimeRepair.Text.Trim();
                if (gioBatDauSua.Length < 4)
                {
                    MessageBox.Show("Giờ bắt đầu sửa chưa đúng định dạng mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtTimeRepair.Focus();
                    return false;
                }
                else if (gioBatDauSua.Length == 4)
                {
                    gioBatDauSua = gioBatDauSua.Insert(2, ":");
                }
                if (!AF.Library.FDateTime.IsDate(ngayBatDauSua + " " + gioBatDauSua + ":00"))
                {
                    MessageBox.Show("Ngày giờ bắt đầu sửa chưa đúng định dạng dd/MM/yyyy mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpRepair.Focus();
                    return false;
                }
                else
                {
                    DateTime repairDate = AF.Library.FDateTime.ConvertDate(ngayBatDauSua + " " + gioBatDauSua + ":00");
                    if (repairDate.Hour > 20 || repairDate.Hour <7)
                    {
                        MessageBox.Show("Giờ bắt đầu sửa nằm ngoài thời gian làm việc", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtTimeRepair.Focus();
                        return false;
                    }
                }
                if (!string.IsNullOrEmpty(ngayBatDauSua) && !string.IsNullOrEmpty(gioBatDauSua)
                    && !string.IsNullOrEmpty(ngayNhanxe) && !string.IsNullOrEmpty(gioNhanxe))
                {
                    DateTime InputDate = ToDate(ngayNhanxe, gioNhanxe);
                    DateTime repairDate = ToDate(ngayBatDauSua, gioBatDauSua);
                    if (InputDate.CompareTo(repairDate) > 0)
                    {
                        MessageBox.Show("Ngày giờ bắt đầu sửa phải lớn hơn ngày giờ nhận xe", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        dtpRepair.Focus();
                        return false;
                    }
                }
                // Ngày giờ kết thúc sửa
                if (string.IsNullOrEmpty(txtfinish.Text.Trim()) || string.IsNullOrEmpty(txtfinishtime.Text.Trim()))
                {
                    MessageBox.Show("Nhập ngày giờ kết thúc sửa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtfinish.Focus();
                    return false;
                }
                string ngayKetThucSua = txtfinish.Text.Trim();
                if (ngayKetThucSua.Length < 8)
                {
                    MessageBox.Show("Ngày kết thúc sửa chưa đúng định dạng dd/MM/yyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtfinish.Focus();
                    return false;
                }
                else if (ngayKetThucSua.Length == 8)
                {
                    ngayKetThucSua = ngayKetThucSua.Insert(2, "/").Insert(5, "/");
                }
                string gioKetThucSua = txtfinishtime.Text.Trim();
                if (gioKetThucSua.Length < 4)
                {
                    MessageBox.Show("Giờ kết thúc sửa chưa đúng định dạng mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtfinishtime.Focus();
                    return false;
                }
                else if (gioKetThucSua.Length == 4)
                {
                    gioKetThucSua = gioKetThucSua.Insert(2, ":");
                }
                if (!AF.Library.FDateTime.IsDate(ngayKetThucSua + " " + gioKetThucSua + ":00"))
                {
                    MessageBox.Show("Ngày giờ kết thúc sửa chưa đúng định dạng ddMMyyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtfinish.Focus();
                    return false;
                }
                else
                {
                    DateTime finishDate = AF.Library.FDateTime.ConvertDate(ngayKetThucSua + " " + gioKetThucSua + ":00");
                    if (finishDate.Hour > 20 || finishDate.Hour<7)
                    {
                        MessageBox.Show("Giờ kết thúc sửa xe nằm ngoài thời gian làm việc", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtfinishtime.Focus();
                        return false;
                    }
                }
                if (!string.IsNullOrEmpty(ngayBatDauSua) && !string.IsNullOrEmpty(gioBatDauSua)
                    && !string.IsNullOrEmpty(ngayKetThucSua) && !string.IsNullOrEmpty(gioKetThucSua))
                {
                    DateTime repairDate = ToDate(ngayBatDauSua, gioBatDauSua);
                    DateTime FinishDate = ToDate(ngayKetThucSua, gioKetThucSua);
                    if (repairDate.CompareTo(FinishDate) > 0)
                    {
                        MessageBox.Show("Ngày giờ kết thúc sửa phải lớn hơn ngày giờ bắt đầu sửa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtfinish.Focus();
                        return false;
                    }
                }
                // Ngày giờ giao
                if (string.IsNullOrEmpty(dtpOutput.Text.Trim()) || string.IsNullOrEmpty(txtTimeOutput.Text.Trim()))
                {
                    MessageBox.Show("Nhập ngày giờ bàn giao xe", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtTimeOutput.Focus();
                    return false;
                }
                string ngayGiaoXe = dtpOutput.Text.Trim();
                if (ngayGiaoXe.Length < 8)
                {
                    MessageBox.Show("Ngày giao xe chưa đúng định dạng dd/MM/yyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpOutput.Focus();
                    return false;
                }
                else if (ngayGiaoXe.Length == 8)
                {
                    ngayGiaoXe = ngayGiaoXe.Insert(2, "/").Insert(5, "/");
                }
                string gioGiaoXe = txtTimeOutput.Text.Trim();
                if (gioGiaoXe.Length < 4)
                {
                    MessageBox.Show("Giờ giao xe chưa đúng định dạng mm:ss", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtTimeOutput.Focus();
                    return false;
                }
                else if (gioGiaoXe.Length == 4)
                {
                    gioGiaoXe = gioGiaoXe.Insert(2, ":");
                }
                if (!AF.Library.FDateTime.IsDate(ngayGiaoXe + " " + gioGiaoXe + ":00"))
                {
                    MessageBox.Show("Ngày giờ bàn giao xe chưa đúng định dạng ddMMyyyy", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dtpOutput.Focus();
                    return false;
                }
                else
                {
                    DateTime OutDate = AF.Library.FDateTime.ConvertDate(ngayGiaoXe + " " + gioGiaoXe + ":00");
                    if (OutDate.Hour > 20 || OutDate.Hour < 7)
                    {
                        MessageBox.Show("Giờ bàn giao xe nằm ngoài thời gian làm việc", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtTimeOutput.Focus();
                        return false;
                    }
                }
                if (!string.IsNullOrEmpty(ngayKetThucSua) && !string.IsNullOrEmpty(gioKetThucSua)
                    && !string.IsNullOrEmpty(ngayGiaoXe) && !string.IsNullOrEmpty(gioGiaoXe)
                    )
                {
                    DateTime FinishDate = ToDate(ngayKetThucSua, gioKetThucSua);
                    DateTime OutputDate = ToDate(ngayGiaoXe, gioGiaoXe);
                    if (FinishDate.CompareTo(OutputDate) > 0)
                    {
                        MessageBox.Show("Ngày giờ bàn giao xe phải lớn hơn ngày giờ kết thúc sửa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        dtpOutput.Focus();
                        return false;
                    }
                }
                // tên khách hàng
                if (string.IsNullOrEmpty(txtCustName.Text))
                {
                    MessageBox.Show("Nhập tên khách hàng", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtCustName.Focus();
                    return false;
                }
                // loại xe
                if (cboModel.SelectedValue == null || (cboModel.SelectedValue!=null && string.IsNullOrEmpty(cboModel.SelectedValue.ToString())))
                {
                    MessageBox.Show("Chọn loại xe", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboModel.Focus();
                    return false;

                }
                // biển số xe
                if (string.IsNullOrEmpty(txtNumberPlate.Text))
                {
                    MessageBox.Show("Nhập biển số xe", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtNumberPlate.Focus();
                    return false;

                }

                if (cboReceiveAgent.SelectedValue == null || (cboReceiveAgent.SelectedValue != null && cboReceiveAgent.SelectedValue.ToString().CompareTo("0")==0))
                {
                    MessageBox.Show("Chọn nhân viên tiếp nhận", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboReceiveAgent.Focus();
                    return false;
                }
                if (cboRepairAgent.SelectedValue == null || (cboRepairAgent.SelectedValue != null && cboRepairAgent.SelectedValue.ToString().CompareTo("0")==0))
                {
                    MessageBox.Show("Chọn kỹ thuật viên sửa chữa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboRepairAgent.Focus();
                    return false;
                }
                if ((checkKTVCungSua.Checked && cmbKTVCungSua.SelectedValue == null) || (checkKTVCungSua.Checked && cmbKTVCungSua.SelectedValue != null && cmbKTVCungSua.SelectedValue.ToString().CompareTo("0") == 0))
                {
                    MessageBox.Show("Chọn nhân viên cùng sửa", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbKTVCungSua.Focus();
                    return false;
                }
                if (cboNVKT.SelectedValue == null || (cboNVKT.SelectedValue != null && cboNVKT.SelectedValue.ToString().CompareTo("0") == 0))
                {
                    MessageBox.Show("Chọn nhân viên kiểm tra xe ra", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboNVKT.Focus();
                    return false;
                }
                if (cboNVTN.SelectedValue == null || (cboNVTN.SelectedValue != null && cboNVTN.SelectedValue.ToString().CompareTo("0") == 0))
                {
                    MessageBox.Show("Chọn nhân viên thu ngân", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboNVTN.Focus();
                    return false;
                }
            }
            return true;
        }
        private PT_CustomerEntity GetCustomerEntity()
        {
            PT_CustomerEntity CusObj = new PT_CustomerEntity();
            // Biển số xe
            CusObj.NumberPlate = txtNumberPlate.Text.Trim();
            // Sổ bảo hành
            CusObj.SBH = txtSBH.Text.Trim();
            // Tên khách hàng
            CusObj.CustName = txtCustName.Text.Trim();
            // Điện thoại nhà
            CusObj.Phone = txtPhone.Text.Trim();
            // Số nhà
            CusObj.AddressNumber = txtAddressNumber.Text.Trim();
            // Tên đường
            CusObj.Address = txtAddress.Text.Trim();
            // Tỉnh
            if (cboProvince.SelectedValue != null && cboProvince.SelectedValue.ToString() != "")
                CusObj.ProvinceCode = int.Parse(cboProvince.SelectedValue + "");
            // Quận
            if (cboDist.SelectedValue != null && cboDist.SelectedValue.ToString() != "")
                CusObj.DistCode = int.Parse(cboDist.SelectedValue + "");
            // Phường
            CusObj.Ward = txtWard.Text.Trim();
            // Loại xe
            CusObj.Model = cboModel.SelectedValue.ToString();

            // Tổng số KM
            try
            {
                CusObj.TotalKms = float.Parse(txtTotalKms.Text);
            }
            catch (Exception ex)
            {
                CusObj.TotalKms = 0;
            }
            // Số khung, số máy 
            CusObj.MachineCode = txtSK.Text + "/" + txtSM.Text;
            return CusObj;
        }
        private PT_ServiceBillEntity GetServiceEntity()
        {
            PT_ServiceBillEntity obj = new PT_ServiceBillEntity();

            // Bill No
            obj.Bill_NO = lblBillCode.Text; // 
            // neu khong co hang muc thi qui dinh la phieu sua chua
            if (gridWage.Rows.Count > 1)
            {
                // Loại phiếu
                if (CheckExistServiceType("RB"))
                    obj.ServiceType = "RB";
                else if (CheckExistServiceType("KTDK"))
                    obj.ServiceType = "KTDK";
                else
                    obj.ServiceType = "SC";
            }
            else
                obj.ServiceType = "SC";
            // Mã phiếu
            obj.QOT_NO = txtQOT_NO.Text.Trim();// VD: 4338
            
            // Ngày giờ nhận xe
            obj.InputDate = InputDateTime;
            // Ngày giờ trả xe
            obj.OutputDate =OutputDateTime;
            // Ngày giờ sửa xe
            obj.RepairDate = RepairDateTime;
            // Ngày giờ hoàn thành
            obj.FinishDate = FinishDateTime;
            
            
            // KTV sửa chữa
            obj.RepairedBy = int.Parse(cboRepairAgent.SelectedValue.ToString());
            // KTV cùng sửa
            if (checkKTVCungSua.Checked)
            {
                obj.RepairedBy2 = int.Parse(cmbKTVCungSua.SelectedValue.ToString());
            }
            else
            {
                obj.RepairedBy2 = 0;
            }
            // Nhân viên tiếp nhận
            obj.ReceivedBy = int.Parse(cboReceiveAgent.SelectedValue.ToString());
            // Nhân viên thu ngân
            obj.Cashier = int.Parse(cboNVTN.SelectedValue.ToString());
            // Nhân viên kiểm tra xe ra
            obj.CheckBy = int.Parse(cboNVKT.SelectedValue.ToString());

            // Biển số xe
            obj.NumberPlate = txtNumberPlate.Text;
            obj.SBH = txtSBH.Text.Trim();
            // Tên khách hàng
            obj.CustName = txtCustName.Text.Trim();
            obj.CustName_noUnicode = AF.Library.FString.GetStandardString(txtCustName.Text.Trim());
            // Điện thoại nhà
            obj.Phone = txtPhone.Text.Trim();
            // Số nhà
            obj.AddressNumber = txtAddressNumber.Text.Trim();
            // Tên đường
            obj.Address = txtAddress.Text.Trim();
            // Tỉnh
            if (cboProvince.SelectedValue != null && cboProvince.SelectedValue.ToString() != "")
                obj.ProvinceCode = int.Parse(cboProvince.SelectedValue + "");
            // Quận
            if (cboDist.SelectedValue != null && cboDist.SelectedValue.ToString() != "")
                obj.DistCode = int.Parse(cboDist.SelectedValue + "");
            // Phường
            obj.Ward = txtWard.Text.Trim();
            // Loại xe
            obj.Model = cboModel.SelectedValue.ToString();

            // Tổng số KM
            try
            {
                obj.TotalKms = float.Parse(txtTotalKms.Text);
            }
            catch (Exception ex)
            {
                obj.TotalKms = 0;
            }
            // Số khung, số máy 
            obj.MachineCode = txtSK.Text + "/" + txtSM.Text;
            obj.Description = txtDescription.Text.Trim();
            // yêu cầu khách hàng
            obj.CustomerRequest = txtYeuCauKhachHang.Text.Trim();
            // Ket qua chan doan
            obj.MotorStatus = txtKetQuaChanDoan.Text.Trim();
            // Tinh trang xe truoc khi sua
            obj.MotorStatusBefore = txtTinhTrangXeTruocKhiSua.Text.Trim();
            // Muc nhien lieu
            obj.Fuellevel = (int)txtNhienLieu.Value;
            return obj;
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            btnExport.UseWaitCursor = true;
            ShowStatusBar("Đang in phiếu");
            Thread mainThread = new Thread(new ThreadStart(CreateBillContent));
            mainThread.Start();
            btnExport.UseWaitCursor = false;
        }
        private void PrintDocument(object sender,WebBrowserDocumentCompletedEventArgs e)
        {
            string keyName = @"Software\Microsoft\Internet Explorer\PageSetup";
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
            {
                if (key != null)
                {
                    string old_footer = key.GetValue("footer") != null ? key.GetValue("footer").ToString() : "";
                    string old_header = key.GetValue("header") != null ? key.GetValue("header").ToString() : "";
                    string old_margin_bottom = key.GetValue("margin_bottom")!=null ? key.GetValue("margin_bottom").ToString() : "";
                    string old_margin_left = key.GetValue("margin_left") != null ? key.GetValue("margin_left").ToString() : "";
                    string old_margin_right = key.GetValue("margin_right") != null ? key.GetValue("margin_right").ToString() : "";
                    string old_margin_top = key.GetValue("margin_top") != null ? key.GetValue("margin_top").ToString() : "";
                    string old_Print_Background = key.GetValue("Print_Background") != null ? key.GetValue("Print_Background").ToString() : "";
                    string old_Shrink_To_Fit = key.GetValue("Shrink_To_Fit") != null ? key.GetValue("Shrink_To_Fit").ToString() : "";
                    key.SetValue("footer", "");
                    key.SetValue("header", "");
                    key.SetValue("margin_bottom", "0.200000");
                    key.SetValue("margin_left", "0.200000");
                    key.SetValue("margin_right", "0.200000");
                    key.SetValue("margin_top", "0.200000");
                    key.SetValue("Print_Background", "yes");
                    key.SetValue("Shrink_To_Fit", "yes");
                    // Print the document now that it is fully loaded.
                    //((WebBrowser)sender).ShowPrintDialog();
                    ((WebBrowser)sender).Print();

                    // Dispose the WebBrowser now that the task is complete. 
                    ((WebBrowser)sender).Dispose();
                    if (!string.IsNullOrEmpty(old_footer))
                        key.SetValue("footer", old_footer);
                    if (!string.IsNullOrEmpty(old_header))
                        key.SetValue("header", old_header);
                    if (!string.IsNullOrEmpty(old_margin_bottom))
                        key.SetValue("margin_bottom", old_margin_bottom);
                    if (!string.IsNullOrEmpty(old_margin_left))
                        key.SetValue("margin_left", old_margin_left);
                    if (!string.IsNullOrEmpty(old_margin_right))
                        key.SetValue("margin_right", old_margin_right);
                    if (!string.IsNullOrEmpty(old_margin_top))
                        key.SetValue("margin_top", old_margin_top);
                    if (!string.IsNullOrEmpty(old_Print_Background))
                        key.SetValue("Print_Background", old_Print_Background);
                    if (!string.IsNullOrEmpty(old_Shrink_To_Fit))
                        key.SetValue("Shrink_To_Fit", old_Shrink_To_Fit);
                }           
            }
        }
        public string getComment(string comment,string type)
        {
            switch (type)
            {
                case "BH":
                    comment += " - Bảo hành";
                    break;
                case "TC":
                    comment += " - Thiện chí";
                    break;
                case "KM":
                    comment += " - Khuyến mãi";
                    break;
                case "GG":
                    comment += " - Giảm giá";
                    break;
            }
            return comment;
        }
        private void CreateBillContent()
        {
            this.Invoke((MethodInvoker)delegate
            {
                try
                {
                    btnExport.Enabled = false;
                    string htmlBill = File.ReadAllText(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/bill.html");
                    DataTable headdt = PT_ServiceBillManager.CreateInstant().GetReportHead(SessionLogin.UserId).Tables[0];
                    htmlBill = htmlBill.Replace("{head}", "HEAD " + headdt.Rows[0]["DEALER_CODE"] + " - " + headdt.Rows[0]["FULL_NAME"]);
                    htmlBill = htmlBill.Replace("{address}", "Số: " + headdt.Rows[0]["HEAD_ADD"]);
                    htmlBill = htmlBill.Replace("{phone&fax}", "ĐT: " + headdt.Rows[0]["HEAD_TEL"] + " - Fax: " + headdt.Rows[0]["HEAD_FAX"]);
                    // Ho ten
                    htmlBill = htmlBill.Replace("{customerName}", txtCustName.Text.Trim());
                    // dien thoai
                    htmlBill = htmlBill.Replace("{phone}", txtPhone.Text.Trim());
                    //Loai xe
                    htmlBill = htmlBill.Replace("{motorType}", cboModel.SelectedValue.ToString());
                    //Bien so
                    htmlBill = htmlBill.Replace("{BSNumber}", txtNumberPlate.Text.Trim());
                    //dia chi
                    string diachi = "";
                    if (!string.IsNullOrEmpty(txtAddressNumber.Text.Trim()))
                        diachi += txtAddressNumber.Text.Trim();
                    if (!string.IsNullOrEmpty(txtAddress.Text.Trim()))
                        diachi += " " + txtAddress.Text.Trim() + ". ";
                    if (!string.IsNullOrEmpty(txtWard.Text.Trim()))
                        diachi += "PHƯỜNG " + txtWard.Text.Trim() + ". ";
                    if (!string.IsNullOrEmpty(cboDist.Text.Trim()))
                        diachi += "QUẬN " + cboDist.Text.Trim().Replace("QUẬN", "").Replace("Quận", "") + ". ";
                    if (!string.IsNullOrEmpty(cboProvince.Text.Trim()))
                        diachi += "TP " + cboProvince.Text.Trim() + ". ";
                    htmlBill = htmlBill.Replace("{diachi}", diachi);
                    //So khung
                    htmlBill = htmlBill.Replace("{KhungNumber}", txtSK.Text.Trim());
                    //So may
                    htmlBill = htmlBill.Replace("{SMNumber}", txtSM.Text.Trim());
                    //So phieu
                    htmlBill = htmlBill.Replace("{sophieu}", txtQOT_NO.Text.Trim());
                    //Ngay gio vao xuong
                    htmlBill = htmlBill.Replace("{inTime}", dtpInput.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeInput.Text.Trim().Replace(":", "").Insert(2, ":"));
                    //Ngay gio len ban sua chua
                    htmlBill = htmlBill.Replace("{repairTime}", dtpRepair.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeRepair.Text.Trim().Replace(":", "").Insert(2, ":"));
                    //Gio hoan tat sua chua
                    htmlBill = htmlBill.Replace("{finishTime}", txtfinish.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtfinishtime.Text.Trim().Replace(":", "").Insert(2, ":"));
                    //Ngay gio giao xe
                    htmlBill = htmlBill.Replace("{outTime}", dtpOutput.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeOutput.Text.Trim().Replace(":", "").Insert(2, ":"));
                    //So KM
                    htmlBill = htmlBill.Replace("{KMNumber}", txtTotalKms.Text.Trim());
                    //yeu cau cua khach hang
                    string yeucau = "";
                    if (string.IsNullOrEmpty(txtYeuCauKhachHang.Text.Trim()))
                        yeucau = "<br/><br/><br/>";
                    else
                    {
                        yeucau = txtYeuCauKhachHang.Text.Trim();
                        if (txtYeuCauKhachHang.Text.Trim().Length < 200)
                            yeucau += "<br/><br/>";
                    }
                    htmlBill = htmlBill.Replace("{Yeucaukhachhang}", yeucau);
                    //ket qua chan doan
                    string ketqua = "";
                    if (string.IsNullOrEmpty(txtKetQuaChanDoan.Text.Trim()))
                        ketqua = "<br/><br/><br/>";
                    else
                    {
                        ketqua = txtKetQuaChanDoan.Text.Trim();
                        if (txtKetQuaChanDoan.Text.Trim().Length < 200)
                            ketqua += "<br/><br/>";
                    }
                    htmlBill = htmlBill.Replace("{ketquachandoan}", ketqua);
                    //tinh trang xe truoc khi sua
                    string tinhtrang = "";
                    if (string.IsNullOrEmpty(txtTinhTrangXeTruocKhiSua.Text.Trim()))
                        tinhtrang = "<br/><br/><br/>";
                    else
                    {
                        tinhtrang = txtTinhTrangXeTruocKhiSua.Text.Trim();
                        if (txtTinhTrangXeTruocKhiSua.Text.Trim().Length < 200)
                            tinhtrang += "<br/><br/>";
                    }
                    htmlBill = htmlBill.Replace("{tinhtrangxetruockhisua}", tinhtrang);
                    //muc nhien lieu
                    string mucnhienlieu = "Mức nhiên liệu:";
                    string space = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    if (txtNhienLieu.Value == 0)
                        mucnhienlieu += space + "E" + space + "|" + space + "|" + space + "|" + space + "F";
                    else if (txtNhienLieu.Value <= 25)
                        mucnhienlieu += space + "E-------|" + space + "|" + space + "|" + space + "F";
                    else if (txtNhienLieu.Value > 25 && txtNhienLieu.Value <= 50)
                        mucnhienlieu += space + "E-------|--------|" + space + "|" + space + "F";
                    else if (txtNhienLieu.Value > 50 && txtNhienLieu.Value <= 75)
                        mucnhienlieu += space + " E-------|--------|--------|" + space + "F";
                    else if (txtNhienLieu.Value > 75 && txtNhienLieu.Value <= 100)
                        mucnhienlieu += space + "E-------|--------|--------|--------F";
                    htmlBill = htmlBill.Replace("{mucnhienlieu}", mucnhienlieu);
                    // Hang muc sua chua
                    float tongtiensuachua = 0;
                    string hangmucSuaChua = "";
                    int tonghangmuc = gridWage.Rows.Count - 1;
                    if (tonghangmuc <= 0)
                    {
                        hangmucSuaChua += "<tr><td style='border-top:1px solid black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px solid black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px solid black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px solid black'>&nbsp;</td></tr>"
                                        + "<tr><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black'>&nbsp;</td></tr>"
                                        + "<tr><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black'>&nbsp;</td></tr>"
                                        + "<tr><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px dotted black;border-right:1px solid black'>&nbsp;</td><td style='border-top:1px solid black;border-right:1px solid black'><b>Tổng số tiền công (1)</b></td><td style='border-top:1px solid black'>&nbsp;</td></tr>";
                    }
                    else
                    {
                        for (int i = 0; i < tonghangmuc; i++)
                            tongtiensuachua += float.Parse(gridWage.Rows[i].Cells["Amount"].Value.ToString());
                        string styleHM = "dotted";
                        string comment = "";
                        if (tonghangmuc >= 4)
                        {
                            int left = 0, right = 0;
                            if (tonghangmuc / 2 < 4)
                            {
                                left = 4;
                                right = tonghangmuc - 4;
                            }
                            else
                            {
                                if (tonghangmuc % 2 == 0)
                                {
                                    left = tonghangmuc / 2 + 1;
                                    right = tonghangmuc - left;
                                }
                                else
                                {
                                    left = tonghangmuc - tonghangmuc / 2;
                                    right = tonghangmuc - left;
                                }
                            }
                            int j = 0;
                            for (int i = 0; i < left; i++)
                            {
                                if (i == 0)
                                    styleHM = "solid";
                                else
                                    styleHM = "dotted";
                                hangmucSuaChua += "<tr>";
                                comment = getComment(gridWage.Rows[i].Cells["Comment"].Value.ToString(), gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString());
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:left'>" + comment + "</td>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:right'>" + gridWage.Rows[i].Cells["Amount"].Value.ToString() + "</td>";
                                if (i == left - 1)
                                {
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px solid black;border-right:1px solid black;text-align:center'><b>Tổng số tiền công(1)</b></td>";
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px solid black;text-align:right;font-weight:bold'>" + String.Format("{0:0,0.###}", tongtiensuachua) + "</td>";
                                }
                                else
                                {
                                    j = i + left;
                                    if (j < tonghangmuc)
                                    {
                                        comment = getComment(gridWage.Rows[j].Cells["Comment"].Value.ToString(), gridWage.Rows[j].Cells["SaleOffReason"].Value.ToString());
                                        hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:left'>" + comment + "</td>";
                                        hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;text-align:right'>" + gridWage.Rows[j].Cells["Amount"].Value.ToString() + "</td>";
                                    }
                                    else
                                    {

                                        hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:left'></td>";
                                        hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;text-align:right'></td>";
                                    }
                                }
                                hangmucSuaChua += "</tr>";
                            }
                        }
                        else
                        {
                            for (int i = 0; i < tonghangmuc; i++)
                            {
                                if (i == 0)
                                    styleHM = "solid";
                                else
                                    styleHM = "dotted";
                                comment = getComment(gridWage.Rows[i].Cells["Comment"].Value.ToString(), gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString());
                                hangmucSuaChua += "<tr>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:left'>" + comment + "</td>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:right'>" + gridWage.Rows[i].Cells["Amount"].Value.ToString() + "</td>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;border-right:1px solid black;text-align:left'></td>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px " + styleHM + " black;text-align:right'></td>";
                                hangmucSuaChua += "</tr>";
                            }
                            for (int i = 0; i < 4 - tonghangmuc; i++)
                            {
                                hangmucSuaChua += "<tr>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:left'>&nbsp;</td>";
                                hangmucSuaChua += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:right'>&nbsp;</td>";
                                if (i == 3 - tonghangmuc)
                                {
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px solid black;border-right:1px solid black;text-align:center'><b>Tổng số tiền công(1)</b></td>";
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px solid black;text-align:right;font-weight:bold'>" + String.Format("{0:0,0.###}", tongtiensuachua) + "</td>";
                                }
                                else
                                {
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:left'>&nbsp;</td>";
                                    hangmucSuaChua += "<td style='color:Black;border-top:1px dotted black;text-align:right'>&nbsp;</td>";
                                }
                                hangmucSuaChua += "</tr>";
                            }
                        }
                    }
                    htmlBill = htmlBill.Replace("{hangmucsuachua}", hangmucSuaChua);
                    // Phu tung thay the
                    float tongtienPhuTung = 0;
                    string tienphutung = "";
                    int rowsCount = 0;
                    string style = "dotted";
                    string tenPhuTung = "";
                    for (int i = 0; i < gridTool.Rows.Count; i++)
                    {
                        if (rowsCount == 0)
                            style = "solid";
                        else
                            style = "dotted";
                        string id = gridTool.Rows[i].Cells["ToolID"].Value + "";
                        if (!string.IsNullOrEmpty(id))
                        {
                            rowsCount++;
                            tienphutung += "<tr>";
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:center'>" + rowsCount + "</td>";
                            string maPhuTung = gridTool.Rows[i].Cells["Part_No"].Value.ToString();
                            if (maPhuTung.Split(' ')[0].Length > 23)
                            {
                                string line1 = maPhuTung.Substring(0, 22);
                                string line2 = maPhuTung.Substring(22, maPhuTung.Length - 22);
                                maPhuTung = line1 + "<br/>" + line2;
                            }
                            tenPhuTung = getComment(gridTool.Rows[i].Cells["ToolName"].Value.ToString(), gridTool.Rows[i].Cells["DiscountReasonT"].Value.ToString());
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:left'>" + maPhuTung + "</td>";
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:left'>" + tenPhuTung + "</td>";
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:center'>" + gridTool.Rows[i].Cells["QTY"].Value.ToString() + "</td>";
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:right'>" + String.Format("{0:0,0.###}", float.Parse(gridTool.Rows[i].Cells["OriginalPriceT"].Value.ToString())) + "</td>";
                            tienphutung += "<td style='color:Black;border-top:1px " + style + " black;text-align:right'>" + String.Format("{0:0,0.###}", float.Parse(gridTool.Rows[i].Cells["Amount"].Value.ToString())) + "</td>";
                            tongtienPhuTung += float.Parse(gridTool.Rows[i].Cells["Amount"].Value.ToString());
                            tienphutung += "</tr>";
                        }
                    }
                    // Phu tung tu mua
                    for (int i = 0; i < GridPTTuMua.Rows.Count-1; i++)
                    {
                        if (rowsCount == 0)
                            style = "solid";
                        else
                            style = "dotted";
                        rowsCount++;
                        string maPhuTung = GridPTTuMua.Rows[i].Cells["Part_NoTM"].Value.ToString();
                        if (maPhuTung.Split(' ')[0].Length > 23)
                        {
                            string line1 = maPhuTung.Substring(0, 22);
                            string line2 = maPhuTung.Substring(22, maPhuTung.Length - 22);
                            maPhuTung = line1 + "<br/>" + line2;
                        }
                        tienphutung += "<tr>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:center'>" + rowsCount + "</td>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:left'>" + maPhuTung + "</td>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:left'>" + GridPTTuMua.Rows[i].Cells["ToolNameTM"].Value.ToString() + "</td>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:center'>" + GridPTTuMua.Rows[i].Cells["QTYTM"].Value.ToString() + "</td>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;border-right:1px solid black;text-align:right'>" + String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[i].Cells["SalePriceTM"].Value.ToString())) + "</td>";
                        tienphutung += "<td style='color:Black;border-top:1px " + style + " black;text-align:right'>" + String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[i].Cells["ThanhTien"].Value.ToString())) + "</td>";
                        tienphutung += "</tr>";
                        tongtienPhuTung += float.Parse(GridPTTuMua.Rows[i].Cells["ThanhTien"].Value.ToString());
                    }
                    if (rowsCount < 15)
                    {
                        for (int i = rowsCount; i < 15; i++)
                        {
                            tienphutung += "<tr>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:center'>&nbsp;</td>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:left'>&nbsp;</td>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:left'>&nbsp;</td>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:center'>&nbsp;</td>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;border-right:1px solid black;text-align:right'>&nbsp;</td>";
                            tienphutung += "<td style='color:Black;border-top:1px dotted black;text-align:right'></td>";
                            tienphutung += "</tr>";
                        }
                    }
                    htmlBill = htmlBill.Replace("{tienphutung}", tienphutung);
                    htmlBill = htmlBill.Replace("{tongtienphutung}", String.Format("{0:0,0.###}", tongtienPhuTung));
                    htmlBill = htmlBill.Replace("{tongsotien}", String.Format("{0:0,0.###}", tongtienPhuTung + tongtiensuachua));
                    //ho ten khach hang
                    htmlBill = htmlBill.Replace("{khachhang}", txtCustName.Text.Trim());
                    //NV tiep nhan
                    htmlBill = htmlBill.Replace("{tiepnhan}", lbNVTiepNhan.Text.Trim());
                    //NV sua chua
                    htmlBill = htmlBill.Replace("{suachua}", lbKTVSuaChua.Text.Trim());
                    //NV kiem tra cuoi
                    htmlBill = htmlBill.Replace("{kiemtracuoi}", lbNVKiemTraXe.Text.Trim());
                    //NV thu ngan
                    htmlBill = htmlBill.Replace("{thungan}", lbNVThuNgan.Text.Trim());
                    File.WriteAllText(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/temp.html", htmlBill, Encoding.UTF8);
                    //System.Diagnostics.Process.Start("IEXPLORE.EXE", System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/temp.html");
                    //System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/temp.html");
                    // Create a WebBrowser instance. 
                    WebBrowser webBrowserForPrinting = new WebBrowser();

                    // Add an event handler that prints the document after it loads.
                    webBrowserForPrinting.DocumentCompleted +=
                        new WebBrowserDocumentCompletedEventHandler(PrintDocument);

                    // Set the Url property to load the document.
                    webBrowserForPrinting.Url = new Uri(@"file:///" + System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/temp.html");
                    btnExport.Enabled = true;
                    EndShowStatusBar();
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message);
                    btnExport.Enabled = true;
                    EndShowStatusBar();
                    MessageBox.Show(ex.Message);
                }
                
            });
            
            //this.Invoke((MethodInvoker)delegate
            //{
            //    // Khoi dong Excel
            //    ComExcel.Application exApp = new ComExcel.Application();

            //    ComExcel.Workbook exBook = exApp.Workbooks.Add(Application.StartupPath + "/ExcelTemplate/Bill.xls");

            //    // Lay sheet 1
            //    ComExcel.Worksheet exSheet = (ComExcel.Worksheet)exBook.Worksheets[1];
            //    //exSheet.Activate();

            //    // dia chi 
            //    DataTable headdt = PT_ServiceBillManager.CreateInstant().GetReportHead(SessionLogin.UserId).Tables[0];
            //    exSheet.Cells[3, 1] = "HEAD " + headdt.Rows[0]["DEALER_CODE"] + " - " + headdt.Rows[0]["FULL_NAME"];
            //    exSheet.Cells[4, 1] = "Số: " + headdt.Rows[0]["HEAD_ADD"];
            //    exSheet.Cells[5, 1] = "ĐT: " + headdt.Rows[0]["HEAD_TEL"] + " - Fax: " + headdt.Rows[0]["HEAD_FAX"];
            //    // Ho ten
            //    exSheet.Cells[7, 1] = "Họ tên khách hàng: " + txtCustName.Text.Trim();
            //    // dien thoai
            //    exSheet.Cells[9, 1] = "Điện thoại: " + txtPhone.Text.Trim();
            //    //Loai xe
            //    exSheet.Cells[10, 1] = "Loại xe: " + cboModel.SelectedValue;
            //    //Bien so
            //    exSheet.Cells[11, 1] = "Biển số: " + txtNumberPlate.Text.Trim();
            //    //dia chi
            //    string diachi = "";
            //    if (!string.IsNullOrEmpty(txtAddressNumber.Text.Trim()))
            //        diachi += txtAddressNumber.Text.Trim();
            //    if (!string.IsNullOrEmpty(txtAddress.Text.Trim()))
            //        diachi += " " + txtAddress.Text.Trim() + ". ";
            //    if (!string.IsNullOrEmpty(txtWard.Text.Trim()))
            //        diachi += "Phường " + txtWard.Text.Trim() + ". ";
            //    if (!string.IsNullOrEmpty(cboDist.Text.Trim()))
            //        diachi += "Quận " + cboDist.Text.Trim() + ". ";
            //    if (!string.IsNullOrEmpty(cboProvince.Text.Trim()))
            //        diachi += "TP " + cboProvince.Text.Trim() + ". ";
            //    exSheet.Cells[6, 5] = "Địa chỉ: " + diachi;
            //    //So khung
            //    exSheet.Cells[10, 5] = "Số khung: " + txtSK.Text.Trim();
            //    //So may
            //    exSheet.Cells[11, 5] = "Số máy: " + txtSM.Text.Trim();
            //    //So phieu
            //    exSheet.Cells[6, 12] = txtQOT_NO.Text.Trim();
            //    //Ngay gio vao xuong
            //    exSheet.Cells[7, 10] = "Ngày/ giờ vào xưởng: " + dtpInput.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeInput.Text.Trim().Replace(":", "").Insert(2, ":");
            //    //Ngay gio len ban sua chua
            //    exSheet.Cells[8, 10] = "Giờ lên bàn nâng sửa chữa: " + dtpRepair.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeRepair.Text.Trim().Replace(":", "").Insert(2, ":");
            //    //Gio hoan tat sua chua
            //    exSheet.Cells[9, 10] = "Giờ hoàn tất sửa chữa: " + txtfinish.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtfinishtime.Text.Trim().Replace(":", "").Insert(2, ":");
            //    //Ngay gio giao xe
            //    exSheet.Cells[10, 10] = "Ngày/ giờ giao xe: " + dtpOutput.Text.Trim().Replace("/", "").Insert(2, "/").Insert(5, "/") + " " + txtTimeOutput.Text.Trim().Replace(":", "").Insert(2, ":");
            //    //So KM
            //    exSheet.Cells[11, 10] = "Số KM: " + txtTotalKms.Text.Trim();
            //    //yeu cau cua khach hang
            //    exSheet.Cells[13, 1] = txtYeuCauKhachHang.Text.Trim();
            //    //ket qua chan doan
            //    exSheet.Cells[13, 5] = txtKetQuaChanDoan.Text.Trim();
            //    //tinh trang xe truoc khi sua
            //    exSheet.Cells[13, 10] = txtTinhTrangXeTruocKhiSua.Text.Trim();
            //    //muc nhien lieu
            //    string mucnhienlieu = "Mức nhiên liệu:";
            //    if (txtNhienLieu.Value == 0)
            //        mucnhienlieu += "        E       |        |        |        F";
            //    else if (txtNhienLieu.Value <= 25)
            //        mucnhienlieu += "        E-------|        |        |        F";
            //    else if (txtNhienLieu.Value > 25 && txtNhienLieu.Value <= 50)
            //        mucnhienlieu += "        E-------|--------|        |        F";
            //    else if (txtNhienLieu.Value > 50 && txtNhienLieu.Value <= 75)
            //        mucnhienlieu += "        E-------|--------|--------|        F";
            //    else if (txtNhienLieu.Value > 75 && txtNhienLieu.Value <= 100)
            //        mucnhienlieu += "        E-------|--------|--------|--------F";
            //    exSheet.Cells[16, 10] = mucnhienlieu;
            //    // Hang muc sua chua
            //    int j = 0;
            //    float tongtiensuachua = 0;
            //    for (int i = 0; i < gridWage.Rows.Count - 1; i++)
            //    {
            //        if (i < 4)
            //        {
            //            exSheet.Cells[19 + i, 1] = gridWage.Rows[i].Cells["Comment"].Value.ToString();
            //            exSheet.Cells[19 + i, 6] = gridWage.Rows[i].Cells["Amount"].Value.ToString();
            //        }
            //        else
            //        {
            //            exSheet.Cells[19 + j, 8] = gridWage.Rows[i].Cells["Comment"].Value.ToString();
            //            exSheet.Cells[19 + j, 13] = "'" + String.Format("{0:0,0.###}", float.Parse(gridWage.Rows[i].Cells["Amount"].Value.ToString()));
            //            j++;
            //        }
            //        tongtiensuachua += float.Parse(gridWage.Rows[i].Cells["Amount"].Value.ToString());
            //    }
            //    exSheet.Cells[22, 13] = "'" + String.Format("{0:0,0.###}", tongtiensuachua);
            //    // Phu tung thay the
            //    j = 0;
            //    float tongtienPhuTung = 0;
            //    for (int i = 0; i < gridTool.Rows.Count - 1; i++)
            //    {
            //        string id = gridTool.Rows[i].Cells["ToolID"].Value + "";
            //        if (!string.IsNullOrEmpty(id))
            //        {
            //            exSheet.Cells[25 + j, 2] = gridTool.Rows[i].Cells["Part_No"].Value.ToString();
            //            exSheet.Cells[25 + j, 4] = gridTool.Rows[i].Cells["ToolName"].Value.ToString();
            //            exSheet.Cells[25 + j, 10] = gridTool.Rows[i].Cells["QTY"].Value.ToString();
            //            exSheet.Cells[25 + j, 11] = "'" + String.Format("{0:0,0.###}", float.Parse(gridTool.Rows[i].Cells["OriginalPriceT"].Value.ToString()));
            //            exSheet.Cells[25 + j, 13] = "'" + String.Format("{0:0,0.###}", float.Parse(gridTool.Rows[i].Cells["Amount"].Value.ToString()));
            //            tongtienPhuTung += float.Parse(gridTool.Rows[i].Cells["Amount"].Value.ToString());
            //            j++;
            //        }
            //    }
            //    // Phu tung tu mua
            //    for (int i = 0; i < GridPTTuMua.Rows.Count - 1; i++)
            //    {
            //        exSheet.Cells[25 + i + j, 2] = GridPTTuMua.Rows[i].Cells["Part_NoTM"].Value.ToString();
            //        exSheet.Cells[25 + i + j, 4] = GridPTTuMua.Rows[i].Cells["ToolNameTM"].Value.ToString();
            //        exSheet.Cells[25 + i + j, 10] = GridPTTuMua.Rows[i].Cells["QTYTM"].Value.ToString();
            //        exSheet.Cells[25 + i + j, 11] = "'" + String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[i].Cells["SalePriceTM"].Value.ToString()));
            //        exSheet.Cells[25 + i + j, 13] = "'" + String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[i].Cells["ThanhTien"].Value.ToString()));
            //        tongtienPhuTung += float.Parse(GridPTTuMua.Rows[i].Cells["ThanhTien"].Value.ToString());
            //    }
            //    //tong tien
            //    exSheet.Cells[40, 13] = "'" + String.Format("{0:0,0.###}", tongtienPhuTung);
            //    exSheet.Cells[41, 13] = "'" + String.Format("{0:0,0.###}", tongtienPhuTung + tongtiensuachua);
            //    //ho ten khach hang
            //    exSheet.Cells[56, 1] = txtCustName.Text.Trim();
            //    //NV tiep nhan
            //    exSheet.Cells[56, 3] = lbNVTiepNhan.Text;
            //    //NV sua chua
            //    exSheet.Cells[56, 5] = lbKTVSuaChua.Text;
            //    //NV kiem tra cuoi
            //    exSheet.Cells[56, 7] = lbNVKiemTraXe.Text;
            //    //NV thu ngan
            //    exSheet.Cells[56, 9] = lbNVThuNgan.Text;
            //    try
            //    {
            //        exSheet.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //    }
            //    exBook.Close(false, false, false);
            //    exApp.Quit();
            //    //exApp.Visible = true;
            //    // hien thi chuong trinh excel
            //    //exApp.Visible = true;
            //    //exBook.ReadOnlyRecommended = false;
            //    System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
            //    System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
            //    btnExport.Enabled = true;
            //    EndShowStatusBar();
            //});
        }
        private void frmBill_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                if (e.KeyCode == Keys.S)
                    btnSave_Click(this, EventArgs.Empty);
                else if (e.KeyCode == Keys.P)
                    btnExport_Click(this, EventArgs.Empty);
            }
        }
        private void txt_KeyDown_ToNextControl(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                this.SelectNextControl((Control)sender, true, true, true, false);
            }
        }

        private void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            //lay danh sach quan huyen
            DataTable tbl = DMS063_VIEWManager.CreateInstant().SelectByP_CODE(cboProvince.SelectedValue.ToString()); ;
            DataRow r = tbl.NewRow();
            r["D_Code"] = "";
            r["D_Name"] = "";
            tbl.Rows.InsertAt(r, 0);
            cboDist.DataSource = tbl;
            cboDist.DisplayMember = "D_Name";
            cboDist.ValueMember = "D_Code";
        }

        /// <summary>
        /// Lay lai phu tung tu DMS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReload_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang load dữ liệu");
            if (string.IsNullOrEmpty(txtQOT_NO.Text.Trim()))
            {
                MessageBox.Show("Vui lòng kiểm tra lại mã phiếu hợp lệ trước khi thực hiện thao tác này");
                return;
            }
            if (MessageBox.Show("Khi bạn lấy lại phụ tùng từ DMS, các phụ tùng hiện tại của phiếu này sẽ bị xóa. Bạn có chắc lấy lại dữ liệu mới từ DMS?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                return;
            if (!string.IsNullOrEmpty(lblBillCode.Text))
            {
                //xoa cac phu tung duoi database
                PT_ToolInBillManager.CreateInstant().DeleteByBillNo_And_ToolType(lblBillCode.Text,0);// trong
                PT_ToolInBillManager.CreateInstant().DeleteByBillNo_And_ToolType(lblBillCode.Text, 1);// ngoai
                //xoa cac danh sach phu tung tren luoi
                ((DataTable)gridTool.DataSource).Rows.Clear();
            }
            else
            {
                if(gridTool.DataSource!=null)
                    ((DataTable)gridTool.DataSource).Rows.Clear();
            }
            LoadToolList(txtQOT_NO.Text,true);
            LoadToolTuMuaList(txtQOT_NO.Text);
            EndShowStatusBar();
        }

        private void btDelSelect_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                for (int i = 0; i < gridWage.RowCount; i++)
                {
                    //MessageBox.Show(gridWage.RowCount.ToString());
                    DataGridViewCheckBoxCell checkSelect = gridWage.Rows[i].Cells["Check"] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        //Guid ID =Guid.Empty;
                        //if (gridWage["ID", j].Value!=null && gridWage["ID", j].Value.ToString() != "")
                        //    ID=(Guid)gridWage["ID", j].Value;
                        //if (ID !=Guid.Empty)
                        //{
                        //    PT_ServiceBillDetailEntity obj = PT_ServiceBillDetailManager.CreateInstant().GetByID(ID);
                        //    if (obj != null)
                        //    {
                        //        obj.IsDeleted = true;
                        //        obj.UpdatedBy = SessionLogin.UserCode;
                        //        obj.UpdatedDate = DateTime.Now;
                        //        try
                        //        {
                        //            PT_ServiceBillDetailManager.CreateInstant().Update(obj);
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //            MessageBox.Show(ex.ToString());
                        //        }
                        //    }
                        //}
                        gridWage.Rows.RemoveAt(checkSelect.RowIndex);
                        i--;
                    }
                }
            }
        }


        void cboAgent_LostFocus(object sender, EventArgs e)
        {

            ComboBox combo = (ComboBox)sender;
            DataTable tbl = (DataTable)(combo.DataSource);
            DataRow[] r = tbl.Select(combo.DisplayMember + "='" + combo.Text + "'");

            if (combo.SelectedItem == null)
            {
                if (r.Length > 0)
                {
                    combo.SelectedValue = r[0][combo.ValueMember];
                }
                else
                {
                    MessageBox.Show("Nhân viên không tồn tại trong hệ thống");
                    combo.Focus();
                }
            }
        }

        void cboProvince_LostFocus(object sender, EventArgs e)
        {

            ComboBox combo = (ComboBox)sender;
            DataTable tbl = (DataTable)(combo.DataSource);
            DataRow[] r = tbl.Select(combo.DisplayMember + "='" + combo.Text + "'");

            if (combo.SelectedItem == null)
            {
                if (r.Length > 0)
                {
                    combo.SelectedValue = r[0][combo.ValueMember];
                }
                else
                {
                    MessageBox.Show("Tỉnh thành không tồn tại trong hệ thống");
                    combo.Focus();
                }
            }
        }

        void cboDist_LostFocus(object sender, EventArgs e)
        {

            ComboBox combo = (ComboBox)sender;
            DataTable tbl = (DataTable)(combo.DataSource);
            DataRow[] r = tbl.Select(combo.DisplayMember + "='" + combo.Text + "'");

            if (combo.SelectedItem == null)
            {
                if (r.Length > 0)
                {
                    combo.SelectedValue = r[0][combo.ValueMember];
                }
                else
                {
                    MessageBox.Show("Quận huyện không tồn tại trong hệ thống");
                    combo.Focus();
                }
            }
        }

        void cboModel_LostFocus(object sender, EventArgs e)
        {

            ComboBox combo = (ComboBox)sender;
            DataTable tbl = (DataTable)(combo.DataSource);
            DataRow[] r = tbl.Select(combo.DisplayMember + "='" + combo.Text + "'");

            if (combo.SelectedItem == null)
            {
                if (r.Length > 0)
                {
                    combo.SelectedValue = r[0][combo.ValueMember];
                }
                else
                {
                    MessageBox.Show("Loại xe không tồn tại trong hệ thống");
                    combo.Focus();
                }
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F4) // Luu tam
            {
                if (btLuuTam.Enabled == true)
                {
                    if (SaveInfo(false))
                        ResetForm();
                }
                else
                    MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                return true;
            }
            if (keyData == Keys.F5) // Luu hoan thành
            {
                if (btnSave.Enabled == true)
                {
                    if (SaveInfo(true))
                        ResetForm();
                }
                else
                    MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cboReceiveAgent_TextChanged(object sender, EventArgs e)
        {
            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cboReceiveAgent.Text);
            if (acc != null)
            {
                lbNVTiepNhan.Text = acc.UserName;
                cboReceiveAgent.Text = acc.DisplayName;
            }
            else
                lbNVTiepNhan.Text = "";
        }

        private void cboRepairAgent_TextChanged(object sender, EventArgs e)
        {
            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cboRepairAgent.Text);
            if (acc != null)
            {
                lbKTVSuaChua.Text = acc.UserName;
                cboRepairAgent.Text = acc.DisplayName;
            }
            else
                lbKTVSuaChua.Text = "";
            if (cboRepairAgent.SelectedValue != null && cmbKTVCungSua.SelectedValue!=null)
            {
                string currentKTVCungSua = cmbKTVCungSua.SelectedValue.ToString();
                DataTable tbl = PT_AccountManager.CreateInstant().GetListAccountExcept(0, cboRepairAgent.SelectedValue.ToString());
                DataRow dr = tbl.NewRow();
                dr["DisplayName"] = "";
                dr["UserId"] = 0;
                tbl.Rows.InsertAt(dr, 0);

                cmbKTVCungSua.DataSource = tbl;
                cmbKTVCungSua.DisplayMember = "DisplayName";
                cmbKTVCungSua.ValueMember = "UserId";

                cmbKTVCungSua.SelectedValue = currentKTVCungSua;
            }
            if (checkKTVCungSua.Checked == true)
            {
                acc = PT_AccountManager.CreateInstant().GetByDisplayName(cmbKTVCungSua.Text);
                if (acc != null)
                {
                    if (string.IsNullOrEmpty(lbKTVSuaChua.Text))
                        lbKTVSuaChua.Text += acc.UserName;
                    else
                        lbKTVSuaChua.Text = lbKTVSuaChua.Text.Split(new char[] { ',' })[0] + ", " + acc.UserName;
                    cmbKTVCungSua.Text = acc.DisplayName;
                }
            }
        }

        private void cboNVKT_TextChanged(object sender, EventArgs e)
        {
            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cboNVKT.Text);
            if (acc != null)
            {
                lbNVKiemTraXe.Text = acc.UserName;
                cboNVKT.Text = acc.DisplayName;
            }
            else
                lbNVKiemTraXe.Text = "";
        }

        private void cboNVTN_TextChanged(object sender, EventArgs e)
        {
            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cboNVTN.Text);
            if (acc != null)
            {
                lbNVThuNgan.Text = acc.UserName;
                cboNVTN.Text = acc.DisplayName;
            }
            else
                lbNVThuNgan.Text = "";
        }

        private void GridPTTuMua_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (e.RowIndex >= 1)
                //{
                GridPTTuMua.Rows[e.RowIndex - 1].Cells["STTTM"].Value = (e.RowIndex).ToString();
            //}
            //gridToolExternal.Rows[e.RowIndex].Cells["STTE"].Value = (e.RowIndex+1).ToString();
        }

        private void GridPTTuMua_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == GridPTTuMua.Columns["PriceTM"].Index)
            {
                if (!AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value))
                {
                    MessageBox.Show("Giá vốn phải là kiểu số. Vui lòng nhập lại.");
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                }
                else
                {
                    
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value)
                    )
                    {
                        float amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) - float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value.ToString());
                        if (amount < 0)
                        {
                            MessageBox.Show("Giá bán phải lớn hơn giá vốn.");
                            GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value = "";
                        }
                        else
                        {

                            GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value = String.Format("{0:0,0.###}", amount);

                            if (GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                              && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                            )
                            {
                                amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                                GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value = String.Format("{0:0,0.###}", amount);
                                float thanhtien=float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                                GridPTTuMua.Rows[e.RowIndex].Cells["ThanhTien"].Value = String.Format("{0:0,0.###}", thanhtien);
                            }
                        }
                    }
                    if (AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
                        GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
                }
            }
            else if (e.ColumnIndex == GridPTTuMua.Columns["QTYTM"].Index)
            {
                if (!AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value))
                {
                    MessageBox.Show("Số lượng phải là kiểu số. Vui lòng nhập lại.");
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                }
                else
                {
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value = String.Format("{0:0,0.###}", amount);
                        
                        if (GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                        {
                            amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                            GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value = String.Format("{0:0,0.###}", amount);
                        }
                    }

                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));

                    if (GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float thanhtien = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["ThanhTien"].Value = String.Format("{0:0,0.###}", thanhtien);
                    }
                }
            }
            else if (e.ColumnIndex == GridPTTuMua.Columns["SalePriceTM"].Index)
            {
                if (!AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value))
                {
                    MessageBox.Show("Giá bán phải là kiểu số. Vui lòng nhập lại.");
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                }
                else
                {
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value!=null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value)
                    )
                    {
                        float amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) - float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["PriceTM"].Value.ToString());
                        if (amount < 0)
                        {
                            MessageBox.Show("Giá bán phải lớn hơn giá vốn.");
                            GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value = "";
                        }
                        GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value = String.Format("{0:0,0.###}", amount);

                        if (GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                        {
                            amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                            GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value = String.Format("{0:0,0.###}", amount);
                        }
                    }
                    if (AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
                        GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float thanhtien = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["ThanhTien"].Value = String.Format("{0:0,0.###}", thanhtien);
                    }
                }
            }
            else if (e.ColumnIndex == GridPTTuMua.Columns["interestTM"].Index)
            {
                if (!AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value))
                {
                    MessageBox.Show("Lãi phải là kiểu số. Vui lòng nhập lại.");
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                }
                else
                {
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float amount = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["interestTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value = String.Format("{0:0,0.###}", amount);
                    }

                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float thanhtien = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["ThanhTien"].Value = String.Format("{0:0,0.###}", thanhtien);
                    }
                }
            }
            else if (e.ColumnIndex == GridPTTuMua.Columns["interestAmountTM"].Index)
            {
                if (!AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["interestAmountTM"].Value))
                {
                    MessageBox.Show("Thành tiền lãi phải là kiểu số. Vui lòng nhập lại.");
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                }
                else
                {
                    GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0.###}", float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()));
                    if (GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) && GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value != null && !string.IsNullOrEmpty(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString())
                      && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value) && AF.Library.Util.IsNumeric(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value)
                    )
                    {
                        float thanhtien = float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["SalePriceTM"].Value.ToString()) * float.Parse(GridPTTuMua.Rows[e.RowIndex].Cells["QTYTM"].Value.ToString());
                        GridPTTuMua.Rows[e.RowIndex].Cells["ThanhTien"].Value = String.Format("{0:0,0.###}", thanhtien);
                    }
                }
            }
        }

        private void gridWage_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == gridWage.Columns["Price"].Index)
                {
                    if (!AF.Library.Util.IsNumeric(gridWage.Rows[e.RowIndex].Cells["Price"].Value))
                    {
                        MessageBox.Show("Vui lòng nhập số tiền đúng.");
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex-1].Selected = true;
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        gridWage.Rows[e.RowIndex].Cells["Price"].Value = String.Format("{0:0,0.###}", float.Parse(gridWage.Rows[e.RowIndex].Cells["Price"].Value.ToString()));
                        gridWage.Rows[e.RowIndex].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(gridWage.Rows[e.RowIndex].Cells["Price"].Value.ToString()));
                    }
                }
                else if (e.ColumnIndex == gridWage.Columns["OutPaid"].Index)
                {
                    if (!AF.Library.Util.IsNumeric(gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value))
                    {
                        MessageBox.Show("Vui lòng nhập số tiền đúng.");
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Selected = true;
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        float thuGCN = gridWage.Rows[e.RowIndex].Cells["Price"].Value != null && AF.Library.Util.IsNumeric(gridWage.Rows[e.RowIndex].Cells["Price"].Value) ? float.Parse(gridWage.Rows[e.RowIndex].Cells["Price"].Value.ToString()) : 0;
                        float chiGCN = float.Parse(gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value.ToString());
                        if (thuGCN < chiGCN)
                        {
                            MessageBox.Show("Chi gia công ngoài không được lớn hơn giá bán.");
                            gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Selected = true;
                            gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        }
                        else
                            gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value = String.Format("{0:0,0.###}", float.Parse(gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value.ToString()));
                    }
                }
                else if (e.ColumnIndex == gridWage.Columns["SaleOff"].Index)
                {
                    if (!AF.Library.Util.IsNumeric(gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value))
                    {
                        MessageBox.Show("Vui lòng nhập số tiền đúng.");
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Selected = true;
                        gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        float saleOff = float.Parse(gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value.ToString());
                        /*
                        if (saleOff < 0)
                        {
                            MessageBox.Show("Số tiền giảm giá không thể là số âm. Vui lòng nhập lại");
                            gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Selected = true;
                            gridWage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        }
                         */
                        if (gridWage.Rows[e.RowIndex].Cells["Price"] != null && AF.Library.Util.IsNumeric(gridWage.Rows[e.RowIndex].Cells["Price"].Value))
                        {
                            float amount = float.Parse(gridWage.Rows[e.RowIndex].Cells["Price"].Value.ToString()) - float.Parse(gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value.ToString());
                            if (amount < 0)
                            {
                                MessageBox.Show("Số tiền giảm giá phải nhỏ hơn giá bán");
                                gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["Amount"].Value = gridWage.Rows[e.RowIndex].Cells["Price"].Value.ToString();
                            }
                            else
                            {
                                gridWage.Rows[e.RowIndex].Cells["Amount"].Value = String.Format("{0:0,0.###}", amount);
                                gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = String.Format("{0:0,0.###}", saleOff);
                            }
                        }
                    }
                }
                else if (e.ColumnIndex == gridWage.Columns["SaleOffReason"].Index)
                {
                    if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"] != null)
                    {
                        if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("BH") == 0 || gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("TC") == 0 || gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("KM") == 0)
                        {
                            gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = gridWage.Rows[e.RowIndex].Cells["Price"].Value;
                            gridWage.Rows[e.RowIndex].Cells["Amount"].Value = "0";
                            gridWage.Rows[e.RowIndex].Cells["SaleOff"].ReadOnly = true;
                        }
                        else if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("GG") == 0)
                        {
                            gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = "0";
                            gridWage.Rows[e.RowIndex].Cells["Amount"].Value = gridWage.Rows[e.RowIndex].Cells["Price"].Value;
                            gridWage.Rows[e.RowIndex].Cells["SaleOff"].ReadOnly = false;
                        }
                        else if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().Trim() != "TT" || gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().Trim() != "")
                        {
                            MessageBox.Show("Lý do giảm giá không đúng. Vui lòng kiểm tra lại.");
                        }
                    }
                }
                else if (e.ColumnIndex == gridWage.Columns["ServiceCode"].Index)
                {
                    //gridWage.BeginEdit(false);
                    try
                    {
                        string ServiceCode = gridWage.Rows[e.RowIndex].Cells["ServiceCode"].Value.ToString();
                        PT_ServiceListEntity serviceObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                        string strServiceType = serviceObj != null ? serviceObj.ServiceType : "";
                        // check servicode này đã tồn tại chưa 
                        if (CheckExistServiceCode(ServiceCode, e.RowIndex))
                        {
                            //khi nao can nhap nhiu HMK thi bo comment doan nay
                            //if (ServiceCode.CompareTo("5HMK") != 0)
                            //{
                                MessageBox.Show("Hạng mục này đã tồn tại. Vui lòng chọn hạng mục khác");
                                gridWage.Rows[e.RowIndex].Cells["ServiceCode"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["Amount"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["Price"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["Comment"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = "";
                                gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value = "";
                                gridWage.CurrentCell = gridWage["ServiceCode", e.RowIndex];
                            //}
                        }
                        else
                        {
                            // neu loai hang muc la RB hoac KTDK thi khong cho phep nhap hang muc la loai RB hoac KTDK nua
                            if (strServiceType == "RB" || strServiceType == "KTDK")
                            {
                                if (CheckExistServiceType(strServiceType, e.RowIndex))
                                {
                                    MessageBox.Show("Loại hạng mục này đã tồn tại. Vui lòng chọn loại hạng mục khác");
                                    gridWage.Rows[e.RowIndex].Cells["ServiceCode"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["Amount"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["Price"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["Comment"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = "";
                                    gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value = "";
                                    gridWage.CurrentCell = gridWage["ServiceCode", e.RowIndex];
                                    return;
                                }
                            }
                            string modelCode = cboModel.SelectedValue.ToString();
                            DataTable objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, modelCode);
                            if (objCond.Rows.Count == 0)
                                objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, "ALL");
                            if (objCond.Rows.Count > 0)
                            {
                                gridWage.Rows[e.RowIndex].Cells["Amount"].ReadOnly = true;
                                gridWage.Rows[e.RowIndex].Cells["Price"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiaBan"].ToString());// gia ban
                                gridWage.Rows[e.RowIndex].Cells["OutPaid"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGCN"].ToString());// gia cong ngoai
                                gridWage.Rows[e.RowIndex].Cells["Comment"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditNoiDung"].ToString()); // noi dung sua chua
                                gridWage.Rows[e.RowIndex].Cells["SaleOff"].ReadOnly = true; // giam gia
                                gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString());// giam gia
                                gridWage.Rows[e.RowIndex].Cells["Comment"].Value = objCond.Rows[0]["ServiceName"].ToString();
                                // Giá bán
                                gridWage.Rows[e.RowIndex].Cells["Price"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                                // Giá tính tiền công thợ
                                gridWage.Rows[e.RowIndex].Cells["AgentPrice"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["AgentPrice"].ToString()));
                                gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value = "";
                                // loại dịch vụ
                                gridWage.Rows[e.RowIndex].Cells["ServiceType"].Value = strServiceType;
                                string lydogiamgia = gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString();
                                if (!string.IsNullOrEmpty(lydogiamgia))
                                {
                                    string sotiengiamgia = gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value.ToString();
                                    if (!string.IsNullOrEmpty(sotiengiamgia))
                                        gridWage.Rows[e.RowIndex].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()) - float.Parse(sotiengiamgia));
                                }
                                else
                                    gridWage.Rows[e.RowIndex].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                                if (gridWage.Rows[e.RowIndex].Cells["Amount"].Value == null)
                                {
                                    gridWage.Rows[e.RowIndex].Cells["Amount"].Value = 0;
                                    gridWage.Rows[e.RowIndex].Cells["OutPaid"].Value = 0;
                                }

                                if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"] != null)
                                {
                                    if (gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("BH") == 0 || gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("TC") == 0 || gridWage.Rows[e.RowIndex].Cells["SaleOffReason"].Value.ToString().CompareTo("KM") == 0)
                                    {
                                        gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = gridWage.Rows[e.RowIndex].Cells["Price"].Value;
                                        gridWage.Rows[e.RowIndex].Cells["Amount"].Value = "0";
                                    }
                                    else
                                    {
                                        gridWage.Rows[e.RowIndex].Cells["SaleOff"].Value = "0";
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    //MessageBox.Show(gridWage.Rows[e.RowIndex].Cells["ServiceCode"].Value.ToString());
                }

            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        private bool CheckExistServiceCode(string serviceCode,int row)
        {
            int count = 0;
            for (int i = 0; i < gridWage.Rows.Count-1; i++)
            {
                string strTempServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                if (serviceCode.CompareTo(strTempServiceCode) == 0)
                    count++;
            }
            if (count > 1 && isExistInMyArrays(serviceCode))
                return true;
            return false;
        }
        private bool isExistInMyArrays(string serviceCode) {
            string[] lstMaHangMuc = new string[7] { "41KTDK", "42KTDK", "43KTDK", "44KTDK", "45KTDK", "46KTDK", "2RAP" };
            for (int i = 0; i < lstMaHangMuc.Length - 1; i++)
                if (serviceCode.CompareTo(lstMaHangMuc[i]) == 0)
                    return true;
            return false;
        }
        private bool CheckExistServiceType(string serviceType, int row)
        {
            int count = 0;
            for (int i = 0; i < gridWage.Rows.Count - 1; i++)
            {
                string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                PT_ServiceListEntity serviceObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                string strTempServiceType = "";
                if (serviceObj != null)
                    strTempServiceType = serviceObj.ServiceType;
                if (serviceType.CompareTo(strTempServiceType) == 0)
                    count++;
            }
            if (count > 1)
                return true;
            return false;
        }
        private void gridWage_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.RowIndex.ToString()+e.ColumnIndex.ToString());
            if (e.RowIndex == -1 && gridWage.Columns[e.ColumnIndex].Name == "Check")
            {
                for (int i = 0; i < gridWage.RowCount-1; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridWage.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void cmbKTVCungSua_TextChanged(object sender, EventArgs e)
        {
            PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cmbKTVCungSua.Text.Trim());
            if (acc != null)
            {
                if (acc.DisplayName != cboRepairAgent.Text)
                {
                    cmbKTVCungSua.Text = acc.DisplayName;
                    if (checkKTVCungSua.Checked == true)
                    {
                        if (string.IsNullOrEmpty(lbKTVSuaChua.Text))
                            lbKTVSuaChua.Text += acc.UserName;
                        else
                            lbKTVSuaChua.Text = lbKTVSuaChua.Text.Split(new char[] { ',' })[0] + ", " + acc.UserName;
                        cmbKTVCungSua.Text = acc.DisplayName;
                    }
                }
                else
                {
                    MessageBox.Show("Nhân viên cùng sửa phải khác nhân viên sửa chữa");
                    cmbKTVCungSua.Text = "";
                    cmbKTVCungSua.Focus();
                }
            }
        }

        private void cmbKTVCungSua_Leave(object sender, EventArgs e)
        {
            if (cmbKTVCungSua.SelectedValue == null)
            {
                MessageBox.Show("Nhân viên tiếp nhận không tồn tại trong hệ thống");
                cmbKTVCungSua.Focus();
            }
        }

        private void checkKTVCungSua_Click(object sender, EventArgs e)
        {
            if (checkKTVCungSua.Checked == true)
            {
                PT_AccountEntity acc = PT_AccountManager.CreateInstant().GetByDisplayName(cmbKTVCungSua.Text);
                if (acc != null)
                {
                    if (string.IsNullOrEmpty(lbKTVSuaChua.Text))
                        lbKTVSuaChua.Text += acc.UserName;
                    else
                        lbKTVSuaChua.Text = lbKTVSuaChua.Text.Split(new char[] { ',' })[0] + ", " + acc.UserName;
                    cmbKTVCungSua.Text = acc.DisplayName;
                }
            }
            else
            {
                lbKTVSuaChua.Text = lbKTVSuaChua.Text.Split(new char[] { ',' })[0];
                cmbKTVCungSua.Text = "";
            }
        }

        private void GridPTTuMua_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(GridPTTuMua.Columns[e.ColumnIndex].Name);
            if (e.RowIndex == -1 && GridPTTuMua.Columns[e.ColumnIndex].Name == "CheckDel")
            {
                for (int i = 0; i < GridPTTuMua.RowCount - 1; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = GridPTTuMua.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void externaldelete_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                for (int i = 0; i < GridPTTuMua.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = GridPTTuMua.Rows[i].Cells["CheckDel"] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        GridPTTuMua.Rows.RemoveAt(checkSelect.RowIndex);
                        i--;
                    }
                }
            }
        }

        private void txtQOT_NO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData ==Keys.Enter)
            {
                txtOrderNo_LostFocus(sender, e);
            }
        }

        private void txtAddressNumber_Leave(object sender, EventArgs e)
        {
            txtAddressNumber.Text = AF.Library.FString.GetString(txtAddressNumber.Text.Trim());
        }

        private void txtAddress_Leave(object sender, EventArgs e)
        {
            //txtAddress.Text = AF.Library.FString.GetString(txtAddress.Text.Trim());
        }

        private void txtWard_Leave(object sender, EventArgs e)
        {
            txtWard.Text = AF.Library.FString.GetString(txtWard.Text.Trim());
        }

        private void txtNumberPlate_Leave(object sender, EventArgs e)
        {
            if (txtNumberPlate.Text.Trim() != "")
            {
                txtNumberPlate.Text = txtNumberPlate.Text.Replace("-", "").Replace(" ", "");
                string temp = txtNumberPlate.Text;
                if (temp.Length > 4)
                    txtNumberPlate.Text = temp.Substring(0, 4) + "-" + temp.Substring(4, temp.Length - 4);

                // get customer by plateNumber
                List<PT_CustomerEntity> lst = PT_CustomerManager.CreateInstant().SelectByNumberPlateLST(txtNumberPlate.Text.Trim());
                if (lst != null && lst.Count > 0)
                {
                    PT_CustomerEntity customerEntity = lst[0];
                    if (customerEntity.NumberPlate.CompareTo("XERA-P") !=0)
                    {
                        txtCustName.Text = customerEntity.CustName;
                        txtSBH.Text = customerEntity.SBH;
                        txtPhone.Text = customerEntity.Phone;
                        txtAddressNumber.Text = customerEntity.AddressNumber;
                        txtAddress.Text = customerEntity.Address;
                        txtWard.Text = customerEntity.Ward;
                        cboProvince.SelectedValue = customerEntity.ProvinceCode;
                        cboDist.SelectedValue = customerEntity.DistCode;
                        cboModel.SelectedValue = customerEntity.Model;
                        string[] strTemp = customerEntity.MachineCode.Split(new char[] { '/' });
                        txtSK.Text = strTemp[0];
                        txtSM.Text = strTemp[1];
                        txtTotalKms.Text = "";
                        txtTotalKms.Focus();
                    }
                }
                else
                {
                    txtCustName.Text = "";
                    txtSBH.Text = "";
                    txtPhone.Text = "";
                    txtAddressNumber.Text = "";
                    txtAddress.Text = "";
                    txtWard.Text = "";
                    cboProvince.SelectedValue = 16;
                    cboDist.Text = "";
                    cboModel.Text = "";
                    txtSK.Text = "";
                    txtSM.Text = "";
                    txtTotalKms.Text = "";
                }
            }
        }

        private void txtSBH_Leave(object sender, EventArgs e)
        {
            if (txtSBH.Text.Trim() != "")
            {
                // get customer by plateNumber
                List<PT_CustomerEntity> lst = PT_CustomerManager.CreateInstant().SelectBySBHLST(txtSBH.Text.Trim());
                if (lst != null && lst.Count > 0)
                {
                    PT_CustomerEntity customerEntity = lst[0];
                    if (customerEntity.NumberPlate.CompareTo("XERA-P") != 0)
                    {
                        txtCustName.Text = customerEntity.CustName;
                        txtPhone.Text = customerEntity.Phone;
                        txtAddressNumber.Text = customerEntity.AddressNumber;
                        txtAddress.Text = customerEntity.Address;
                        txtWard.Text = customerEntity.Ward;
                        cboProvince.SelectedValue = customerEntity.ProvinceCode;
                        cboDist.SelectedValue = customerEntity.DistCode;
                        cboModel.SelectedValue = customerEntity.Model;
                        string[] strTemp = customerEntity.MachineCode.Split(new char[] { '/' });
                        txtSK.Text = strTemp[0];
                        txtSM.Text = strTemp[1];
                        txtTotalKms.Text = "";
                        txtTotalKms.Focus();
                    }
                }
                else if(string.IsNullOrEmpty(txtNumberPlate.Text.Trim()))
                {
                    txtCustName.Text = "";
                    txtPhone.Text = "";
                    txtAddressNumber.Text = "";
                    txtAddress.Text = "";
                    txtWard.Text = "";
                    cboProvince.SelectedValue = 16;
                    cboDist.Text = "";
                    cboModel.Text = "";
                    txtSK.Text = "";
                    txtSM.Text = "";
                    txtTotalKms.Text = "";
                }
            }
        }

        public void AfterLoadGridHangMuc()
        {
            try
            {
                for (int i = 0; i < gridWage.Rows.Count - 1; i++)
                {
                    string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                    PT_ServiceListEntity serviceObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                    string strServiceType = serviceObj != null ? serviceObj.ServiceType : "";
                    string modelCode = cboModel.SelectedValue.ToString();
                    DataTable objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, modelCode);
                    if (objCond.Rows.Count == 0)
                        objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, "ALL");
                    if (objCond.Rows.Count > 0)
                    {
                        gridWage.Rows[i].Cells["Amount"].ReadOnly = true;
                        gridWage.Rows[i].Cells["OutPaid"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGCN"].ToString());// gia cong ngoai
                        gridWage.Rows[i].Cells["Comment"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditNoiDung"].ToString()); // noi dung sua chua
                        gridWage.Rows[i].Cells["SaleOff"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString()); // giam gia
                        gridWage.Rows[i].Cells["SaleOffReason"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString());// giam gia
                        gridWage.Rows[i].Cells["Price"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiaBan"].ToString());// gia ban
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void cboModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < gridWage.Rows.Count-1; i++)
            {
                string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                PT_ServiceListEntity serviceObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                string strServiceType = serviceObj != null ? serviceObj.ServiceType : "";
                
                string modelCode = cboModel.SelectedValue.ToString();
                DataTable objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, modelCode);
                if (objCond.Rows.Count == 0)
                    objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, "ALL");
                if (objCond.Rows.Count > 0)
                {
                    gridWage.Rows[i].Cells["Amount"].ReadOnly = true;
                    gridWage.Rows[i].Cells["Price"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiaBan"].ToString());// gia ban
                    gridWage.Rows[i].Cells["OutPaid"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGCN"].ToString());// gia cong ngoai
                    gridWage.Rows[i].Cells["Comment"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditNoiDung"].ToString()); // noi dung sua chua
                    gridWage.Rows[i].Cells["SaleOff"].ReadOnly = true; // giam gia
                    gridWage.Rows[i].Cells["SaleOffReason"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString());// giam gia
                    gridWage.Rows[i].Cells["Comment"].Value = objCond.Rows[0]["ServiceName"].ToString();
                    // Giá bán
                    gridWage.Rows[i].Cells["Price"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                    // Giá tính tiền công thợ
                    gridWage.Rows[i].Cells["AgentPrice"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["AgentPrice"].ToString()));
                    gridWage.Rows[i].Cells["OutPaid"].Value = "";
                    // loại dịch vụ
                    gridWage.Rows[i].Cells["ServiceType"].Value = strServiceType;
                    string lydogiamgia = gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString();
                    if (!string.IsNullOrEmpty(lydogiamgia))
                    {
                        string sotiengiamgia = gridWage.Rows[i].Cells["SaleOff"].Value.ToString();
                        if (!string.IsNullOrEmpty(sotiengiamgia))
                            gridWage.Rows[i].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()) - float.Parse(sotiengiamgia));
                    }
                    else
                        gridWage.Rows[i].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                    if (gridWage.Rows[i].Cells["Amount"].Value == null)
                    {
                        gridWage.Rows[i].Cells["Amount"].Value = 0;
                        gridWage.Rows[i].Cells["OutPaid"].Value = 0;
                    }
                }
                if (gridWage.Rows[i].Cells["SaleOffReason"] != null)
                {
                    if (gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("BH") == 0 || gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("TC") == 0 || gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("KM") == 0)
                    {
                        gridWage.Rows[i].Cells["SaleOff"].Value = gridWage.Rows[i].Cells["Price"].Value;
                        gridWage.Rows[i].Cells["Amount"].Value = "0";
                    }
                    else
                    {
                        gridWage.Rows[i].Cells["SaleOff"].Value = "0";
                    }
                }

                //string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                //PT_ServiceListEntity serviceObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                //string strServiceType = serviceObj != null ? serviceObj.ServiceType : "";
                //string modelCode = cboModel.SelectedValue.ToString();
                //if (strServiceType == "RB" || strServiceType == "GCN" || strServiceType == "KTDK" || strServiceType == "HMK")
                //    modelCode = "ALL";
                //DataTable objCond = PT_ServiceListManager.CreateInstant().GetByService_Model(ServiceCode, modelCode);
                //if (objCond.Rows.Count > 0)
                //{
                //    gridWage.Rows[i].Cells["Comment"].Value = objCond.Rows[0]["ServiceName"].ToString();
                //    gridWage.Rows[i].Cells["Price"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                //    string lydogiamgia = gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString();
                //    if (!string.IsNullOrEmpty(lydogiamgia))
                //    {
                //        string sotiengiamgia = gridWage.Rows[i].Cells["SaleOff"].Value.ToString();
                //        if (!string.IsNullOrEmpty(sotiengiamgia))
                //            gridWage.Rows[i].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()) - float.Parse(sotiengiamgia));
                //    }
                //    else
                //        gridWage.Rows[i].Cells["Amount"].Value = String.Format("{0:0,0.###}", float.Parse(objCond.Rows[0]["Price"].ToString()));
                //    if (gridWage.Rows[i].Cells["Amount"].Value == null)
                //    {
                //        gridWage.Rows[i].Cells["Amount"].Value = 0;
                //        gridWage.Rows[i].Cells["OutPaid"].Value = 0;
                //    }

                //    gridWage.Rows[i].Cells["Amount"].ReadOnly = true;
                //    gridWage.Rows[i].Cells["Price"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiaBan"].ToString());// gia ban
                //    gridWage.Rows[i].Cells["OutPaid"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGCN"].ToString());// gia cong ngoai
                //    gridWage.Rows[i].Cells["Comment"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditNoiDung"].ToString()); // noi dung sua chua
                //    gridWage.Rows[i].Cells["SaleOff"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString()); // giam gia
                //    gridWage.Rows[i].Cells["SaleOffReason"].ReadOnly = !bool.Parse(objCond.Rows[0]["CanEditGiamGia"].ToString());// giam gia
                //}
                //if (gridWage.Rows[i].Cells["SaleOffReason"] != null)
                //{
                //    if (gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("BH") == 0 || gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("TC") == 0 || gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString().CompareTo("KM") == 0)
                //    {
                //        gridWage.Rows[i].Cells["SaleOff"].Value = gridWage.Rows[i].Cells["Price"].Value;
                //        gridWage.Rows[i].Cells["Amount"].Value = "0";
                //    }
                //}
            }
        }
        public string GetTotalInfo()
        { 
            // bill info
            string info = "THÔNG TIN KHÁCH HÀNG:";
            info += "\nMã phiếu : " + txtQOT_NO.Text + "\nNgày giờ nhận: " + dtpInput.Text+" "+txtTimeInput.Text + "\nNgày giờ bắt đầu sửa: " + dtpRepair.Text+" "+txtTimeRepair.Text
                               + "\nNgày giờ kết thúc sửa: "+txtfinish.Text+" "+txtfinishtime.Text+"\nNgày giờ giao xe: "+dtpOutput.Text+" "+txtTimeOutput.Text
                               + "\nTên khách hàng: " + txtCustName.Text + "\nĐiện thoại: " + txtPhone.Text + "\nSố nhà: " + txtAddressNumber.Text + "\nĐường: " + txtAddress.Text + "\nPhường: " + txtWard.Text
                               + "\nTỉnh: " + cboDist.SelectedText + "\nQuận: " + cboProvince.SelectedText + "\nLoại xe: " + cboModel.SelectedText + "\nBiển số: " + txtNumberPlate.Text + "\nSố khung/Số máy: " + txtSK.Text+"/"+txtSM.Text
                               + "\nSố KM: " + txtTotalKms.Text + "\nNV tiếp nhận: " + cboReceiveAgent.Text + "\nNV Sửa chữa: " + cboRepairAgent.Text + "\nNV Cùng sửa: " + cmbKTVCungSua.Text + "\nNV Kiểm tra xe ra: " + cmbKTVCungSua.Text + "\nNV thu ngân: " + cboNVTN.Text;
            string infotext = "";
            // bill detail
            for (int i = 0; i < gridWage.Rows.Count; i++)
            {
                if (gridWage.Rows[i].Cells["ServiceCode"] != null && gridWage.Rows[i].Cells["Comment"].Value != null
                    && gridWage.Rows[i].Cells["Amount"].Value != null && gridWage.Rows[i].Cells["OutPaid"].Value != null
                    && gridWage.Rows[i].Cells["SaleOff"].Value != null && gridWage.Rows[i].Cells["SaleOffReason"].Value != null
                    && gridWage.Rows[i].Cells["Price"].Value != null && gridWage.Rows[i].Cells["AgentPrice"].Value != null)
                {
                    // Loại phiếu
                    string ServiceCode = gridWage.Rows[i].Cells["ServiceCode"].Value.ToString();
                    // Nội dung sửa chữa
                    string comment = gridWage.Rows[i].Cells["Comment"].Value.ToString();
                    // Thành tiền
                    string amount = gridWage.Rows[i].Cells["Amount"].Value.ToString();
                    // Chi GCN
                    string outPaid = gridWage.Rows[i].Cells["OutPaid"].Value.ToString();
                    // Số tiền giảm giá
                    string SaleOff = gridWage.Rows[i].Cells["SaleOff"].Value.ToString();
                    // Lý do giảm giá
                    string SaleOffReason = gridWage.Rows[i].Cells["SaleOffReason"].Value.ToString();
                    // Giá bán 
                    string Price = gridWage.Rows[i].Cells["Price"].Value.ToString();
                    // Giá trị tính tiền công thợ
                    string AgentPrice = gridWage.Rows[i].Cells["AgentPrice"].Value.ToString();
                    // ServiceType
                    string serviceType = gridWage.Rows[i].Cells["ServiceType"].Value.ToString();
                    PT_ServiceListEntity SObj = PT_ServiceListManager.CreateInstant().GetByServiceCode(ServiceCode);
                    string ServiceName = "";
                    if (SObj != null)
                        ServiceName = SObj.ServiceName;
                    infotext += "\nHạng mục " + (i + 1).ToString() + ":" + ServiceName + ",Nội dung: " + comment + ",Giá bán: " + Price
                                + ",Giá công thợ: " + AgentPrice + ",Lý do giảm giá: " + SaleOffReason + ",Số tiền giảm giá: " + SaleOff
                                + ",Thành tiền: " + amount + ",Chi GCN: " + outPaid;

                }
            }
            info += "\rDANH SÁCH HẠNG MỤC: " + infotext;

            infotext = "";
            // phu tung trong
            for (int i = 0; i < gridTool.Rows.Count; i++)
            {
                string id = gridTool.Rows[i].Cells["ToolID"].Value + "";
                // Mã phụ tùng
                string partNO = gridTool.Rows[i].Cells["Part_NO"].Value + "";
                // Tên phụ tùng
                string partName = gridTool.Rows[i].Cells["ToolName"].Value + "";
                // Thành tiền
                string amount = gridTool.Rows[i].Cells["Amount"].Value + "";
                // Giá gốc
                string Originalprice = gridTool.Rows[i].Cells["OriginalPriceT"].Value + "";
                // Giảm giá
                string DisCountPriceT = gridTool.Rows[i].Cells["DisCountPriceT"].Value + "";
                // Lý do giảm giá
                string DiscountReason = gridTool.Rows[i].Cells["DiscountReasonT"].Value + "";
                // Số lượng
                string QTY = gridTool.Rows[i].Cells["QTY"].Value + "";
                // Loại phụ tùng
                string ToolType = gridTool.Rows[i].Cells["ToolType"].Value + "";
                // IsOil
                string IsOil = gridTool.Rows[i].Cells["IsOilT"].Value + "";
                infotext += "\nPhụ tùng " + (i + 1).ToString() + ": " + "Mã phụ tùng:" + partNO + ",Giá bán: " + Originalprice + ",Giảm giá: " + DisCountPriceT + ",Lý do giảm giá: " + DiscountReason + ",Số lượng: " + QTY + ",Thành tiền: " + amount;
            }
            info += "\rDANH SÁCH NHỚT + PHỤ TÙNG TRONG + PHỤ TÙNG NGOÀI: " + infotext;
            
            infotext = "";
            // phu tung tu mua
            for (int i = 0; i < GridPTTuMua.Rows.Count; i++)
            {
                if (GridPTTuMua.Rows[i].Cells["STTTM"].Value != null)
                {
                    string partNO = GridPTTuMua.Rows[i].Cells["Part_NOTM"].Value + "";
                    string partName = GridPTTuMua.Rows[i].Cells["ToolNameTM"].Value + "";
                    // so luong 
                    string QTY = GridPTTuMua.Rows[i].Cells["QTYTM"].Value + "";
                    // gia von 
                    string originalPrice = GridPTTuMua.Rows[i].Cells["PriceTM"].Value + "";
                    // gia ban
                    string price = GridPTTuMua.Rows[i].Cells["SalePriceTM"].Value + "";
                    infotext += "\nPhụ tùng " + (i + 1).ToString() + ": " + ",Mã phụ tùng: " + partNO + ",Giá vốn: " + originalPrice + ",Giá bán: " + price + ",Số lượng: " + QTY + ",Thành tiền: " + float.Parse(QTY) * float.Parse(price);
                }
            }
            info += "\rDANH SÁCH PHỤ TÙNG TỰ MUA: " + infotext;
            return info;
        }

        private void cboModel_TextChanged(object sender, EventArgs e)
        {
            PT_HondaModelEntity obj = PT_HondaModelManager.CreateInstant().GetByModelCode(cboModel.Text.Trim().ToUpper());
            if (obj != null)
            {
                cboModel.Text = obj.ModelCode;
            }
        }

        private void cboProvince_TextChanged(object sender, EventArgs e)
        {
            List<DMS064Entity> lst = DMS064Manager.CreateInstant().SelectByP_NAMELST(cboProvince.Text.Trim().ToUpper());
            if (lst != null && lst.Count > 0)
            {
                cboProvince.Text = lst[0].P_NAME;
            }
        }

        private void cboDist_TextChanged(object sender, EventArgs e)
        {
            List<DMS063_VIEWEntity> lst = DMS063_VIEWManager.CreateInstant().SelectByD_NAMELST(cboDist.Text.Trim().ToUpper());
            if (lst != null && lst.Count > 0)
            {
                cboDist.Text = lst[0].D_NAME;
            }
        }

        private void gridWage_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;

                //xu ly autocomplete            
                ComboBox cbo = (ComboBox)e.Control;
                iR = gridWage.CurrentCell.RowIndex;
                iC = gridWage.CurrentCell.ColumnIndex;
                cbo.Leave += new EventHandler(cbo_Leave);
            }
           
        }
        int iR = -1;
        int iC = -1;
        //xu ly auto complete cua grid
        void cbo_Leave(object sender, EventArgs e)
        {
            ComboBox cbo = (ComboBox)sender;
            DataTable tbl = (DataTable)cbo.DataSource;
            DataRow[] r = tbl.Select(cbo.DisplayMember + "='" + cbo.Text + "'");
            if (r.Length > 0)
            {
                gridWage.Rows[iR].Cells[iC].Value = r[0][cbo.ValueMember];
            }
            cbo.Leave -= new EventHandler(cbo_Leave);
            iR = -1;
            iC = -1;
        }


        private void ResetForm()
        {
            LoadModel_User("");
            txtQOT_NO.Text = "";
            lblBillCode.Text = "";
            txtQOT_NO.Enabled = true;
            dtpInput.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtTimeInput.Text = DateTime.Now.ToString("HH:mm");
            dtpRepair.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtTimeRepair.Text = DateTime.Now.ToString("HH:mm");
            txtfinish.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtfinishtime.Text = DateTime.Now.ToString("HH:mm");
            dtpOutput.Text = DateTime.Now.ToString("dd/MM/yyyy");
            txtTimeOutput.Text = DateTime.Now.ToString("HH:mm");
            txtCustName.Text = "";
            txtPhone.Text = "";
            txtAddressNumber.Text = "";
            txtAddress.Text = "";
            txtWard.Text = "";
            cboDist.Text = "";
            cboModel.Text = "";
            txtNumberPlate.Text = "";
            txtSBH.Text = "";
            txtSK.Text = "";
            txtSM.Text = "";
            txtTotalKms.Text = "";
            cboReceiveAgent.Text = "";
            cboRepairAgent.Text = "";
            checkKTVCungSua.Checked = false;
            cmbKTVCungSua.Text = "";
            cboNVKT.Text = "";
            cboNVTN.Text = "";
            LoadBillDetail("RESET");
            gridTool.DataSource = null;
            LoadToolTuMuaList("RESET");

            lblTotal.Text = "0";
            lbTienDichVu.Text = "0";
            lbTienPhuTung.Text = "0";
            lblTotal2.Text = "KHÔNG ĐỒNG";
            txtQOT_NO.Focus();
            txtQOT_NO.TabStop = true;
            lbKTVSuaChua.Text = "";
            txtDescription.Text = "";
            txtDescription.Text = "";
            txtYeuCauKhachHang.Text = "";
            txtKetQuaChanDoan.Text = "";
            txtTinhTrangXeTruocKhiSua.Text = "";
            txtNhienLieu.Value = 0;
            //hien thi cai Title tab o tren khi sua chua phieu
            this.Parent.Text = "Thêm phiếu dịch vụ";
            return;
        }

        private void checkKTVCungSua_Enter(object sender, EventArgs e)
        {
            checkKTVCungSua.BackColor = System.Drawing.Color.Blue;
        }

        private void checkKTVCungSua_Leave(object sender, EventArgs e)
        {
            checkKTVCungSua.BackColor = System.Drawing.Color.Transparent;
        }

        private void txtNhienLieu_ValueChanged(object sender, EventArgs e)
        {
            progressBarNhienLieu.Value = (int)txtNhienLieu.Value;
        }     
    }
}
